Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why click function triggers twice for custom component in Angular 2

My custom component click function is triggered twice - both custom component's event and sample level event are triggered.

Here's my Plunker:

https://plnkr.co/edit/wp2iWh7OStdPm5uXsWbP?p=preview

like image 529
Abinaya Avatar asked Feb 08 '17 11:02

Abinaya


People also ask

Why is my click event firing twice?

Answers. Post the code of the object you are clicking on, and the event that is firing twice. Usually this is caused by declaring it in the OnClick event, as well as Handles Something.

How does angular handle click event?

Events are handled in Angular using the following special syntax. Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right. Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.


1 Answers

Because you have bound it twice on the child component and on the parent component. The mouseEvent propagates from the child component to the parent component by default. You can stop propagation of event to parent component.

Template:

<div (click)="divClick($event)">Custom Div Clcik here!</div>

Class:

divClick(event) {
    event.stopPropagation();
    alert("divClick");
}
like image 158
Roman C Avatar answered Oct 19 '22 20:10

Roman C