You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 16(Material)动态菜单:[matMenuTriggerFor]不识别变量标识符

解决Angular Material动态Mat-Menu绑定问题

你的问题出在动态模板引用变量的写法错误,Angular不支持ref-{{seccion[0]}}="matMenu"这种动态生成模板引用名的方式,而且[matMenuTriggerFor]需要绑定的是MatMenu实例,不是字符串名称。

修正方案:

1. 组件类代码(保留原数据结构,新增菜单实例映射逻辑)

import { Component, ViewChildren, QueryList, MatMenu, OnInit } from '@angular/core';

@Component({
  // 组件元数据保持不变
})
export class TuComponent implements OnInit {
  menuAyuda: any[][] = [];

  @ViewChildren('menu') menus!: QueryList<MatMenu>;
  private menuMap = new Map<string, MatMenu>();

  ngOnInit() {
    this.menuAyuda.push(['General']);
    this.menuAyuda.push(['Expedientes', ['Alta Expediente', 'Alta Lote', 'Alta Línea Adjudicación', 'Alta Línea Renovación', 'Recepción Administrativa', 'Recepción a Inventario']]);
    this.menuAyuda.push(['Inventario', ['Búsquedas','Mover Artículos entre Unidades', 'Asignar CUF-Sistema-Subsistema']]);
  }

  ngAfterViewInit() {
    // 将菜单ID和实例存入映射表
    this.menus.forEach(menu => {
      if (menu.id) {
        this.menuMap.set(menu.id, menu);
      }
    });
  }

  // 根据菜单名称获取对应实例
  getMenu(menuName: string): MatMenu | undefined {
    return this.menuMap.get(menuName);
  }
}

2. 修正后的HTML代码

<ng-container *ngFor="let seccion of menuAyuda">
  <!-- 无子菜单的项 -->
  <span *ngIf="!seccion[1] || seccion[1]?.length === 0">
    <button mat-menu-item>{{seccion[0]}}</button>
  </span>

  <!-- 有子菜单的项 -->
  <ng-container *ngIf="seccion[1] && seccion[1].length > 0">
    <button mat-button [matMenuTriggerFor]="getMenu(seccion[0])">
      {{seccion[0]}}
    </button>
    <mat-menu [id]="seccion[0]" #menu="matMenu">
      <button mat-menu-item *ngFor="let subitem of seccion[1]">
        {{subitem}}
      </button>
    </mat-menu>
  </ng-container>
</ng-container>

核心逻辑说明:

  • 给每个mat-menu设置唯一的[id](对应菜单名称seccion[0]),同时用静态模板变量#menu标记所有菜单
  • 通过@ViewChildren获取所有MatMenu实例,在视图初始化完成后,将ID与实例存入Map映射表
  • 按钮的[matMenuTriggerFor]通过调用getMenu方法,传入菜单名称获取对应的实例,完成绑定

内容的提问来源于stack exchange,提问作者Stalky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 07:27:31