简体   繁体   中英

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

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

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

my believe is: add emit solves it as well

Template

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

Class

@Output()
divClick = new EventEmitter<any>().emit;

Try:

event.preventDefault();

instead of:

event.stopPropagation();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM