Prevent parent click event when child is clicked angular

When working with Angular, we can prevent the click event on a parent element when a child element is clicked by using event.stopPropagation().

Here’s an example to explain this:

    
// HTML template
<div (click)="onParentClick()">
    <div (click)="onChildClick($event)">
        Child Element
    </div>
</div>

// Component class
export class MyComponent {
    onParentClick() {
        console.log("Parent click event");
    }
    
    onChildClick(event: Event) {
        event.stopPropagation();
        console.log("Child click event");
    }
}
    
    

In this example, we have a parent div element with a click event handler defined in the onParentClick() method. Inside the parent div, we have a child div element which also has a click event handler defined in the onChildClick() method.

When the child div is clicked, the onChildClick() method is called and we use event.stopPropagation() to prevent the click event from bubbling up to the parent div. This means that the onParentClick() method will not be executed.

Without event.stopPropagation(), both the onChildClick() and onParentClick() methods would be executed when the child div is clicked.

Leave a comment