Open Angular Material Menu Programmatically using ViewChild on MatMenuTrigger

天大地大妈咪最大 提交于 2020-03-23 07:09:31

问题


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:


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



来源:https://stackoverflow.com/questions/53792202/open-angular-material-menu-programmatically-using-viewchild-on-matmenutrigger

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!