Why click function triggers twice for custom compo

2019-07-22 02:46发布

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

2条回答
在下西门庆
2楼-- · 2019-07-22 02:59

Your problem is that you call click() event on your parent component and in your child component: here:

<cus-div (click)="onClick()"></cus-div>

and here:

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

remove the click event on your <cus-div></cus-div> of your click event and it will trigger once

查看更多
劳资没心,怎么记你
3楼-- · 2019-07-22 03:04

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");
}
查看更多
登录 后发表回答