Stop the spread of the click event of all children
To stop the propagation of the click event of all child elements:
<div (click)="openModal()"> <span>Click in this element open the modal</span> <li>Click in this element open the modal too</li> <p>Click in this element open the modal too</p> <input type="button">Click in this element open the modal too</input> </div> I want to open the modal only with the div element. Is there any way to do this?
If you want to conditionally execute logic only when the parent div element is clicked (and not when the event propagates when the child element is clicked), you can check if the currentTarget event matches the target value .
- The
currentTargetproperty always refers to the element to which the event is bound. In this case, the(click)event is bound to thedivelement. event.targetproperty always refers to the element that sent the event.
Therefore, if you only want to filter out the instances that the child clicks on, and you want to filter out common events substantially, you can check if $event.currentTarget $event.target $event.currentTarget :
public openModal ($event) { if ($event.currentTarget === $event.target) { // Clicked on the parent `div` element with the // click event binding `(click)="openModal($event)"` console.log('Clicked the parent, not the child.'); } } <div (click)="openModal($event)"> <span>...</span> <p>...</p> </div>