Angular 2 prevent click on parent when clicked on child

Ashik Basheer picture Ashik Basheer · Dec 29, 2016 · Viewed 21.6k times · Source

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)" />

Answer

Stefan Svrkota picture Stefan Svrkota · Dec 29, 2016

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)" />