Angular matMenuTriggerFor 以编程方式 [英] Angular matMenuTriggerFor programmatically
本文介绍了Angular matMenuTriggerFor 以编程方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在一个从数组动态填充的 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 matMenuTriggerFor 以编程方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文