cristian Oliveira
cristian Oliveira

Reputation: 45

Click event on ngfor loop running twice. angular

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

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

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

Upvotes: 0

Views: 766

Answers (1)

KamLar
KamLar

Reputation: 428

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

Upvotes: 1

Related Questions