Close matMenu on Dialog Open?
Asked Answered
O

3

5

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.

Oregano answered 11/4, 2019 at 15:55 Comment(0)
W
10

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()"
>
Woodall answered 11/4, 2019 at 16:9 Comment(2)
There are 4 must haves that worked for me: 1. menu with an id like #menu="matMenu, 2. calling menuTrigger.closeMenu() in the template 3. having @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; 4. explicit calling this.trigger.closeMenu(); Also @bugs answer help in figuring this out.Dublin
The bottom example should be (click)="openUpdateQuestionDialog($event,currentSelectedQuestion); menuTrigger.closeMenu()" have tested it works.Impossibility
T
5

You can do that by calling closeMenu() on the MatMenuTrigger directive (see here for docs).

Something like

<button mat-button #menuTrigger="matMenuTrigger" [matMenuTriggerFor]="menu">Menu</button>
<mat-menu #menu="matMenu">
  <button mat-menu-item>Item 1</button>
  <button mat-menu-item>Item 2</button>
</mat-menu>

---

@ViewChild('menuTrigger') trigger;
...
this.trigger.closeMenu()

Demo

Tasteless answered 11/4, 2019 at 16:7 Comment(0)
V
-1

Without @ViewChild:

<mat-menu #moreMenu="matMenu" #menuTrigger="matMenuTrigger" [matMenuTriggerFor]="moreMenu">
  <button mat-menu-item (click)="doYourThing(); menuTrigger.closeMenu()">More</button>
</mat-menu>
Vedetta answered 22/2 at 1:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.