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?
stopPropagation() Event Method The stopPropagation() method prevents propagation of the same event from being called. Propagation means bubbling up to parent elements or capturing down to child elements.
To stop the click event from propagating to the <div> element, you have to call the stopPropagation() method in the event handler of the button: btn. addEventListener('click', (e) => { e. stopPropagation(); alert('The button was clicked!
stopPropagation() – It prevents the event from propagating (or “bubbling up”) the DOM.
event.stopPropagation() This will stop any parent component's event from firing. To use this: Make sure to pass the event object as a parameter. Use the stopPropagation method on the event object above your code within your event handler function.
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.
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.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With