问题是由于Angular 13中的动态建造和Angular Material菜单之间的一些不兼容性引起的。要解决这个问题,可以使用以下代码示例:
首先,在app.module.ts文件中引入所需的模块:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatMenuModule } from '@angular/material/menu';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatMenuModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
然后,在组件中建立菜单的数组:
export interface MenuItem {
name: string;
icon: string;
link: string;
children?: MenuItem[];
}
export const MENUITEMS: MenuItem[] = [
{
name: 'Home',
icon: '',
link: '/home',
children: []
},
{
name: 'Menu One',
icon: '',
link: '',
children: [
{
name: 'Submenu One',
icon: '',
link: '/menu/one/submenu/one'
},
{
name: 'Submenu Two',
icon: '',
link: '/menu/one/submenu/two'
}
]
},
{
name: 'Menu Two',
icon: '',
link: '',
children: [
{
name: 'Submenu One',
icon: '',
link: '/menu/two/submenu/one'
},
{
name: 'Submenu Two',
icon: '',
link: '/menu/two/submenu/two'
}
]
}
];
然后,在组件类之中,使用以下方法来构建菜单:
import { Component } from '@angular/core';
import { MatMenu } from '@angular/material/menu';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import