in3pi2
in3pi2

Reputation: 907

Stop click event propagation of all children

How to stop the click event propagation of all children 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 a way to do it?

Upvotes: 6

Views: 3352

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241208

If you want to conditionally execute logic only when the parent div element is clicked (and not when the event propagates when clicking on a child element), then you could check to see if the event's currentTarget property is equal to the target property.

  • The currentTarget property always refers to the element that the event is bound to. In this case, the (click) event is bound to the div element.
  • The event.target property always refers to the element that dispatched the event.

Therefore, if you only want to filter out instances where a child element is clicked and you want to essentially filter out propagated events, then you can check to see if $event.currentTarget is equal to $event.target:

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>

Upvotes: 10

Related Questions