I have a click event nested one level. When i click on the child the expected function is called but the parent's function is also called. Here is the code
<li class="task-item" *ngFor="let task of tasks" (click)="showTask(task.name)"> <input type="checkbox" [ngModel]="task.taskStatus" (ngModelChange)="changeTaskStatus($event)" /> </li>
So when the checkbox changes changeTaskStatus()
and the showTask()
called together. I want the parent to keep quiet when checkbox changes. How do I achieve this? It was easy to handle this in Angular 1
Things I've tried that failed
Used $event.stopPropagation()
in the checkbox's click event that changed nothing
<input type="checkbox" [ngModel]="task.taskStatus" (click)="$event.stopPropagation()" (ngModelChange)="changeTaskStatus($event)" />
event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.
stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.
You need to use stopPropagation()
for checkbox event:
<input type="checkbox" [ngModel]="task.taskStatus" (ngModelChange)="changeTaskStatus($event);$event.stopPropagation()" />
It prevents further propagation of the current event in the capturing and bubbling phases. You can read more here. Also, you probably need to add stopPropagation()
to click
event of checkbox, but I'm not 100% sure:
<input type="checkbox" [ngModel]="task.taskStatus" (click)="$event.stopPropagation()" (ngModelChange)="changeTaskStatus($event)" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With