...">

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?

+5
source share
1 answer

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 .

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> 
+9
source

Source: https://habr.com/ru/post/1263947/


All Articles