6

How can an Angular Material menu be opened programmatically using Template Reference Variable on button trigger, which is accessed in component using ViewChild?

The menu opens normally on click, but I'd like to open it programmatically on mouseover.

(mouseover) event handler gives error: Cannot read property 'openMenu' of undefined.

So why is clickHoverMenuTrigger undefined in the component?

Here's the component html

<button mat-icon-button [matMenuTriggerFor]="clickHoverMenu" 
  #clickHoverMenuTrigger (mouseover)="openOnMouseOver()">
  <mat-icon>notifications</mat-icon>
</button>

Here's the component typescript

@ViewChild(MatMenuTrigger) clickHoverMenuTrigger: MatMenuTrigger;

openOnMouseOver() {
  this.clickHoverMenuTrigger.openMenu();
}

This method is documented here https://material.angular.io/components/menu/overview

Same problem raised and answered here How do I access mat menu trigger from typescript (I don't have the reputation to comment on that)

It looks like I'm doing exactly what is stated in the documentation and the StackOverflow solution above.

As clickHoverMenuTrigger is undefined, it must be an issue with @ViewChild.

Code on Stackblitz. Open console to see error.

1 Answer 1

22

Just change the @ViewChild to

@ViewChild('clickHoverMenuTrigger') clickHoverMenuTrigger: MatMenuTrigger;

Overall code should be:

<h1>2 buttons, 2 Menus</h1>

<ol>
  <li>Standard Material Button opens menu on click </li>
  <li>Same, but with event handler to open menu on mouseover</li>
</ol>

<button mat-icon-button [matMenuTriggerFor]="clickMenu"
  #clickMenuTrigger="matMenuTrigger">
  <mat-icon>touch_app</mat-icon>
</button>

<button mat-icon-button [matMenuTriggerFor]="clickHoverMenu" 
  #clickHoverMenuTrigger="matMenuTrigger" (mouseover)="openOnMouseOver()">
  <mat-icon>notifications</mat-icon>
</button>

<mat-menu #clickMenu="matMenu">
  <button mat-menu-item>Settings</button>
  <button mat-menu-item>Help</button>
</mat-menu>

<mat-menu #clickHoverMenu="matMenu">
  <button mat-menu-item>New items</button>
</mat-menu>

ts:

export class AppComponent {

  @ViewChild('clickHoverMenuTrigger') clickHoverMenuTrigger: MatMenuTrigger;

  openOnMouseOver() {
    this.clickHoverMenuTrigger.openMenu();
  }
}

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Many thanks, the Material documentation is incorrect then (material.angular.io/components/menu/overview) and so is the accepted answer here stackoverflow.com/questions/47080338/… @ViewChild(MatMenuTrigger) trigger: MatMenuTrigger; I also missed assignment of template reference variable to matMenuTrigger > #clickHoverMenuTrigger="matMenuTrigger"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.