Angular 2 clicks arrow several times inside ngFor

I have a very strange problem (never seen) with my component. I am trying to delete a row by clicking on a button inside the ngFor list. When I have only one line, it works, but when it contains more than one line, the event is fired twice, once for a good line and once for the first line (after deleting another line):

<label> <div class="tag" *ngFor="let o of selectedOptions;"> <span class="tag-text">{{ o.textContent }}</span> <button (click)="removeTag(o)" type="button" class="fa fa-times"></button> </div> </label> 

And here is my witch method called twice (only if there is another option):

 public removeTag (option: NxtSelectOptionComponent) { this.selectedOptions = [ ...this.selectedOptions.filter(o => o !== option), ] } 

I tried to use splice, I tried to add stopPropagation ... I do not understand that I did this a lot of time, and this is the first time I see it.

EDIT: the removeTag method is called when I click on the .tag element, so when I click on the button, it is called twice, but I can’t understand why ... the attribute (click) only on the button

The problem is resolved: I found the problem ... The FYI shortcut label clicks on the button, so if you have any (click) attribute, it will fire twice.

+7
source share
3 answers

In fact, the second click will be called by the parent element. The default behavior of browsers is to trigger a click on the login as soon as the parent receives the click.

Use

 event.preventDefault(); 

to stop the second trigger.

+4
source

try it

 <div *ngFor="let user of users; let i=index" > {{user.name}} <div> <a class="btn btn-danger" (click)="removeUser(i)">-</a> </div> </div> removeUser(i): void { this.users.splice(i, 1); } 
0
source

Complete solution:

 <label> <div class="tag" *ngFor="let o of selectedOptions;"> <span class="tag-text">{{ o.textContent }}</span> <button (click)="removeTag(o, $event)" type="button" class="fa fa-times"></button> </div> </label> 

Then the method that receives the event:

 public removeTag (option: NxtSelectOptionComponent, event) { event.preventDefault(); // This is needed to prevent the click event from firing twice on a label this.selectedOptions = [ ...this.selectedOptions.filter(o => o !== option), ] } 
0
source

Source: https://habr.com/ru/post/1012736/


All Articles