Search code examples
angularangular-materialmaterial-design

Close matMenu on Dialog Open?


I am triggering a dialog on clicking an item in matMenu but the concern is that matMenu doesn't close when dialog is open. I want it to close it as soon as dialog box opens up, it closes when you click somewhere in the page, but I want it to close once dialog box opens.

this is the code-snippet for matMenu.

  <button mat-icon-button [matMenuTriggerFor]="menu" #menuTrigger="matMenuTrigger" (mouseup)="menuTrigger.closeMenu()">
    <mat-icon>more_vert</mat-icon>
  </button>
  <mat-menu #menu="matMenu" xPosition="before" >
    <button mat-menu-item (click)="openUpdateQuestionDialog($event,currentSelectedQuestion)">
      Edit
    </button>
    <button mat-menu-item (click)="confirmDeleteQuestion($event,currentSelectedQuestion)">
      Delete
    </button>
  </mat-menu>

I am trying different ways to make it work, but no luck.


Solution

  • There are a couple of options for closing the mat menu (mat menu trigger).

    From the docs, you can use the matMenuTrigger from the ts via a "child" decorator (ViewChild or ContentChild potentially based on your location of the menu to the functionality):

    class MyComponent {
      @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger;
    
      someMethod() {
        this.trigger.closeMenu(); // <-- put this in your dialog open method
      }
    }
    

    I did not test this, but it may also be possible to call the close from the template as well:

    <button mat-menu-item
      (click)="openUpdateQuestionDialog($event,currentSelectedQuestion) && menuTrigger.closeMenu()"
    >