skip to Main Content

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

2

Answers


  1. 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.

    @Component({
      selector: 'app-root',
      standalone: true,
      template: `
        <div class="parent" (click)="onClick($event)">
          Parent
          <div class="menu-container">
            <div class="menu">Menu</div>
            <div class="child child-2">Child 2</div>
            <div class="child child-3">Child 3</div>
          </div>
        </div>
      `,
    })
    export class App  {
      name = 'Angular';
    
      protected onClick(ev: MouseEvent): void {
        // if within parent div but not within menu-container div
        const shouldShowAlert =
        ev.target instanceof HTMLElement && !!ev.target.closest('.parent') && !ev.target.closest('.menu-container')
    
        if (shouldShowAlert) {
          this.openAlert();
        }
      }
    
      public openAlert() {
        alert('Details View');
      }
    }
    

    More information about the closest method can be found here.

    Login or Signup to reply.
  2. 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();
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search