Angular matMenuTriggerFor以编程方式

时间:2018-05-17 14:22:08

标签: angular angular-material

我在Angular项目中使用matMenu,该项目是从数组动态填充的。此菜单可以有一个级别的子菜单。我的菜单定义数组如下所示:

{
  text: string,
  subMenuName: string,
  subMenuItems: [{
    text: string,
    onClick(): void
  }]
}

我正在尝试在HTML中构建此菜单,如下所示:

<mat-menu #menu="matMenu">
  <button *ngFor="let item of menuItems" [matMenuTriggerFor]="menuItem.subMenuName" mat-menu-item>
    {{ item.text }}
  </button>
</mat-menu>

<ng-container *ngFor="item of menuItems">
  <mat-menu #item.subMenuName="matMenu">
    <button *ngFor="let subItem of item.subMenuItems (click)="subItem.onClick();">
      {{ subItem.text }}
    </button>
  </mat-menu>
</ng-container>

当我尝试运行它时,它没有令人满意,并且它给出了以下错误:

ERROR TypeError: Cannot read property 'subscribe' of undefined
    at MatMenuTrigger.push../node_modules/@angular/material/esm5/menu.es5.js.MatMenuTrigger.ngAfterContentInit

1 个答案:

答案 0 :(得分:3)

解决方案是创建一个递归引用其自身的组件。下面的代码:

TS

import { Component, Input, ViewChild } from '@angular/core';
import { NavItem } from './nav-item/nav-item';

@Component({
  selector: 'app-menu-item',
  templateUrl: './menu-item.component.html',
  styleUrls: ['./menu-item.component.css']
})
export class MenuItemComponent {
  @Input('items')
  public  items: NavItem[];

  @ViewChild('childMenu')
  public childMenu;

  constructor() { }

}

HTML

<mat-menu #childMenu="matMenu" [overlapTrigger]="false">
  <span *ngFor="let child of items">
    <span *ngIf="child.children && child.children.length > 0">
      <button mat-menu-item color="primary" [matMenuTriggerFor]="menu.childMenu">
        <mat-icon>{{ child.iconName }}</mat-icon>
        <span>{{ child.displayName }}</span>
      </button>
      <app-menu-item #menu [items]="child.children"></app-menu-item>
    </span>
    <span *ngIf="!child.children || child.children.length === 0">
      <button mat-menu-item (click)="child.onClick();">
        <mat-icon>{{ child.iconName }}</mat-icon>
        <span>{{ child.displayName }}</span>
      </button>
    </span>
  </span>
</mat-menu>

NavItem是接口:

export interface NavItem {
  displayName: string;
  iconName?: string;
  children?: NavItem[];

  onClick?(): void;
}

然后,我只需要在HTML中引用<app-menu-item [items]="..">