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
<
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)" />
Just you need to add $event.stopPropagation() code on Child div on click event
<input (click)="onChildClickFunction();$event.stopPropagation()"/>
This is known as Event Bubbling. Events are first handled by the innermost element and then propagate to the outer elements until they reach the root.
<div *ngFor="let item of userList">
<div (click)="setUserData(item)">
<a (click)="getUserDetails(item.user.id)">Name - {{item.user.name}}</a>
</div>
</div>
In this case, when you click on username or tag, it will first call inner element i.e. getUserDetails() and the root element i.e. setUserData().
So, to prevent this event bubbling, just add
event.preventDefault();
in defination of getUserDetails($event) or
<a (click)="getUserDetails(item.user.id); $event.stopPropagation();">Name - {{item.user.name}}</a>
That's all you need to you.