Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 prevent click on parent when clicked on child

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)" /> 
like image 887
Ashik Basheer Avatar asked Dec 29 '16 13:12

Ashik Basheer


People also ask

How do I stop parent click event in react?

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.

How do you stop event propagation from parent to child?

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.


1 Answers

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)" /> 
like image 165
Stefan Svrkota Avatar answered Sep 20 '22 17:09

Stefan Svrkota