本文介绍了使用 MatMenuTrigger 上的 ViewChild 以编程方式打开 Angular Material Menu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用按钮触发器上的模板参考变量以编程方式打开 Angular Material 菜单,该变量在组件中使用 ViewChild 访问?

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.

(鼠标悬停)事件处理程序给出错误:无法读取未定义的属性openMenu".

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

那么为什么在组件中没有定义 clickHoverMenuTrigger 呢?

So why is clickHoverMenuTrigger undefined in the component?

这是组件 html

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

这是组件打字稿

@ViewChild(MatMenuTrigger) clickHoverMenuTrigger: MatMenuTrigger;

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

此处记录了此方法 https://material.angular.io/components/menu/概述

这里提出并回答了同样的问题 我如何访问 mat来自打字稿的菜单触发器(我没有对此发表评论的声誉)

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)

看起来我正在按照上面的文档和 StackOverflow 解决方案中的说明进行操作.

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

由于 clickHoverMenuTrigger 未定义,所以它一定是 @ViewChild 的问题.

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

Stackblitz 上的代码.打开控制台查看错误.

Code on Stackblitz. Open console to see error.

推荐答案

只需将 @ViewChild 更改为

@ViewChild('clickHoverMenuTrigger') clickHoverMenuTrigger: MatMenuTrigger;

整体代码应该是:

<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();
  }
}

演示

这篇关于使用 MatMenuTrigger 上的 ViewChild 以编程方式打开 Angular Material Menu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 08:41