I have an Angular component with nested div elements. I want to trigger a click event on the parent div, but if the menu child div is clicked, the parent div’s click event should not be triggered.
main.ts
@Component({
selector: 'app-root',
standalone: true,
template: `
<div (click)="openAlert()" class="parent">Parent
<div class="menu">Menu</div>
<div class="child child-2">Child 2</div>
<div class="child child-3">Child 3</div>
</div>
`,
})
export class App {
name = 'Angular';
public openAlert() {
alert('Details View');
}
}
2
Answers
Inside your click handler function you can inspect the click event’s target and detect whether the click was from within the parent div and not a child div. I put a menu-wrapper around the child divs to simplify your example.
More information about the
closest
method can be found here.You can use event.stopPropagation() in the click event handler for the "menu" div. This method stops the event will propagating to the parent element.
Here is how you can update your code: