angularangular-material

Nested mat-menu closes unexpectedly when opening second menu


I'm using Angular 19 with Angular Material 3 (latest version with MDC-based components) in a project, and I'm running into an issue when working with nested mat-menu elements. What I'm trying to do is

Here is how it is currently implemented:

<!-- Trigger for First Menu -->
<button
  [matMenuTriggerFor]="candidatMenu"
  class="cursor-pointer"
>
  <mat-icon>more_vert</mat-icon>
</button>

<!-- Calendar Menu Trigger -->
<ng-container *ngIf="showCalendar">
  <button
    mat-icon-button
    [matMenuTriggerFor]="menuCal"
    aria-label="Add event"
  >
    <mat-icon>event</mat-icon>
  </button>
</ng-container>

<!-- Calendar Mat Menu -->
<mat-menu #menuCal="matMenu">
  <button mat-menu-item (click)="doSomething()">
    <mat-icon>add</mat-icon>
    <span>Option 1</span>
  </button>
  <button mat-menu-item (click)="doSomethingElse()">
    <mat-icon>add</mat-icon>
    <span>Option 2</span>
  </button>
  <button mat-menu-item (click)="anotherAction()">
    <mat-icon>add</mat-icon>
    <span>Option 3</span>
  </button>
</mat-menu>

Is there something I am missing here?


Solution

  • When you click on the second nested menu, it is triggering the close logic of the first nested menu. You need to do something like

    $event.stopPropagation()
    

    in order to stop the original closing logic.

    In your case

    <button
        mat-icon-button
        [matMenuTriggerFor]="menuCal"
        aria-label="Add event"
        (click)=($event.stopPropagation())
    >
    

    Something like that should work.