How to open mat-menu programmatically?

Roel picture Roel · Nov 5, 2017 · Viewed 43.7k times · Source

Im trying to trigger opening a menu when clicking mat-nav-list item.

HTML

<mat-nav-list>
    <mat-list-item (click)="onOpenMenu(menu)" *ngFor="let i of data">
        <div mat-line>
            {{ i.name }}
        </div>
        <p mat-line>
            {{ i.email }}
        </p>
        <button mat-icon-button [matMenuTriggerFor]="menu">
            <mat-icon>more_vert</mat-icon>
        </button>
    </mat-list-item>
    <mat-menu #menu="matMenu">
        <button mat-menu-item>View profile</button>
        <button mat-menu-item>Add contact</button>
    </mat-menu>
</mat-nav-list>

TS

onOpenMenu(menu: any): void {
   // menu doesn't have any openMenu() function 
   // which is of course not a trigger object but a menu itself.
   console.log(menu);
}

I have been trying to look at this issue on github which is closer to my situation. but in my case i have a dynamic list of items which i wanted to open a menu every click.

DEMO

Answer

yurzui picture yurzui · Nov 5, 2017

You need to get hold of MatMenuTrigger instance from [matMenuTriggerFor] element

#menuTrigger="matMenuTrigger"  [matMenuTriggerFor]="menu"

where

  • #menuTrigger is the template reference variable

  • matMenuTrigger is exportAs property of MatMenuTrigger metadata

and then simply call

(click)="menuTrigger.openMenu()"

Stackblitz example

Read more about template reference variable here