Angular MatMenuTrigger用于编程 [英] Angular matMenuTriggerFor programmatically

查看:411
本文介绍了Angular MatMenuTrigger用于编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a matMenu in an Angular project which is populated dynamically from an array. This menu can have one level of sub-menu's. My menu definition array looks like this:

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

我试图按以下方式以HTML构建此菜单:

I am trying to build this menu in HTML as follows:

<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>

当我尝试运行此代码时,它未遵循并且给出了以下错误:

When I try to run this, it is not compliing and it is giving the following error:

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

推荐答案

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

Solution was to create a component which referenced itself recursively. Code below:

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]="..">.

Then I simply need to reference <app-menu-item [items]=".."> in my HTML.

这篇关于Angular MatMenuTrigger用于编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆