Why click function triggers twice for custom component in Angular 2

自作多情 提交于 2019-12-11 02:19:11

问题


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


回答1:


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");
}



回答2:


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:


Try:

event.preventDefault();

instead of:

event.stopPropagation();


来源:https://stackoverflow.com/questions/42111971/why-click-function-triggers-twice-for-custom-component-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!