Angular Material导航栏添加点击事件与路由跳转问题
解决方案
1. 调整MenuItem结构,区分路由跳转与方法执行
原来的href字段无法同时满足路由跳转和方法调用需求,我们需要给菜单项添加不同属性来区分两种操作:
- 路由跳转项:用
routerLink存储目标路由地址 - 方法执行项(如logout):用
action存储要调用的方法名称
修改组件中的menuItems数组:
import { Router } from '@angular/router'; // ... export class HeaderComponent implements OnInit{ constructor(private userService: UserService, private router: Router) {} isLoggedIn: boolean = false; menuItems: MenuItem[] = [ { label: 'Offers', icon: 'notes', routerLink: '/offers', showOnMobile: false, showOnTablet: true, showOnDesktop: true }, { label: 'Bookmark', icon: 'bookmark', routerLink: '/bookmark', showOnMobile: false, showOnTablet: true, showOnDesktop: true }, { label: 'Application', icon: 'video_stable', routerLink: '/application', showOnMobile: false, showOnTablet: false, showOnDesktop: true }, { label: 'Claim', icon: 'send', routerLink: '/claim', showOnMobile: false, showOnTablet: false, showOnDesktop: true }, { label: 'Forum', icon: 'forum', routerLink: '/forum', showOnMobile: true, showOnTablet: true, showOnDesktop: true }, { label: 'log out', icon: 'logout', action: 'logout', showOnMobile: false, showOnTablet: false, showOnDesktop: false }, { label: 'Profile', icon: 'profile', routerLink: '/profile', showOnMobile: false, showOnTablet: false, showOnDesktop: false }, ]; ngOnInit(): void {} logout(){ this.userService.signout(); } // 通用方法执行函数 executeAction(actionName: string) { if (typeof this[actionName] === 'function') { this[actionName](); } } }
2. 修改HTML模板,绑定路由与点击事件
在循环渲染的按钮上,根据菜单项的属性动态绑定routerLink或点击事件:
顶部导航按钮修改:
<button mat-button *ngFor="let item of menuItems" [fxShow]="item.showOnDesktop" [fxShow.xs]="item.showOnMobile" [fxShow.sm]="item.showOnTablet" [routerLink]="item.routerLink" (click)="item.action && executeAction(item.action)" > <mat-icon class="mr">{{item.icon}}</mat-icon> {{item.label}} </button>
下拉菜单按钮修改:
<button mat-menu-item [routerLink]="item.routerLink" (click)="item.action && executeAction(item.action)" > <mat-icon class="mr">{{item.icon}}</mat-icon> {{item.label}} </button>
关键说明
- 路由跳转依赖Angular Router模块,确保已在项目中导入并配置好路由
executeAction函数用于统一处理方法调用,避免在模板中写复杂逻辑- 原来的
href属性不适合Angular的路由和事件绑定逻辑,改用Angular原生的routerLink和(click)语法才能正常触发操作
内容的提问来源于stack exchange,提问作者Mahmoud Timoumi
相关产品推荐
相关产品推荐

