Search code examples
javascriptangulartypescript

How to trigger a click event on a parent div excluding a specific child element in Angular?


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.

Demo@StackBlitz

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');
  }
}

Solution

  • 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:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <div (click)="openAlert()" class="parent">Parent
          <div (click)="stopPropagation($event)" 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');
      }
    
      public stopPropagation(event: MouseEvent) {
        event.stopPropagation();
      }
    }