Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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!

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading