Home > Back-end >  Click event on ngfor loop running twice. angular
Click event on ngfor loop running twice. angular

Time:11-21

I've found an interesting problem that I can't bypass.

I have the follwing *ngFor loop with a click event.

<label  *ngFor="let status of statuses; trackBy: id"
    (click)="filterByCategory(status.name)">{{ status.name }}
    <span  [attr.data-chip-state]="status.name">
    {{ partners | counter: status.name }}</span>
    <input type="checkbox" />
    <span ></span>
</label>

the click event fn filterByCategory() is a simple process, responsible for add or remove string from an array to then filter an array of objects.

  filterByCategory(category, event: Event) { 
    let verify = this.filterArr.includes(category);
   
    if (!verify) { 
      this.filterArr.push(category)
    } else {    
      let indexOfCategory = this.filterArr.indexOf(category);
      this.filterArr.splice(indexOfCategory, 1);
    } 
  
    this.filteredPartners = this.partners.filter(partner => {
      return this.filterArr.includes(partner.partner_status.name);
    }) 
  }

When the event is fired, it runs twice and the if statement first adds the string and then removes it.

enter image description here

Does any one has a way to resolve this?

Thank you!

CodePudding user response:

I believe it's because you attached click event listener to label. If you click on the label you trigger the event for the first time, but then the checkbox is being clicked and it triggers once again click event.

Because you are using label here - you can freely move click listener to checkox. So instead of what you have, you can do it like this:

<label  *ngFor="let status of statuses; trackBy: id">{{ status.name }}
<span  [attr.data-chip-state]="status.name">
{{ partners | counter: status.name }}</span>
<input type="checkbox" (click)="filterByCategory(status.name)" />
<span ></span>
  • Related