如何将Angular的<mat-button-toggle-group>绑定到应用路由实现导航?
你遇到的NG8002错误是因为mat-button-toggle组件本身不支持routerLink指令——RouterLink默认仅绑定到<a>或<button>这类原生元素上。不过不用换组件重写样式,有两种简便方式实现需求:
方法一:通过mat-button-toggle-group的选中事件结合Router跳转
这种方式利用组件的change事件监听选中状态变化,通过Angular的Router服务手动跳转路由,同时还能保持按钮组的选中状态与当前路由同步。
1. 组件代码
在组件类中注入Router和ActivatedRoute,用于跳转路由和获取当前路由信息:
import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-nav-toggle', templateUrl: './nav-toggle.component.html', styleUrls: ['./nav-toggle.component.css'] }) export class NavToggleComponent implements OnInit { currentRoute: string = ''; constructor(private router: Router, private route: ActivatedRoute) {} ngOnInit(): void { // 获取当前路由路径,初始化按钮组选中状态 this.currentRoute = this.route.snapshot.url.join('/'); // 监听路由变化,实时更新选中状态 this.router.events.subscribe(() => { this.currentRoute = this.route.snapshot.url.join('/'); }); } onToggleChange(event: any): void { // 跳转至选中按钮对应的路由 this.router.navigate([event.value]); } }
2. 模板代码
给mat-button-toggle-group绑定value(同步当前路由)和(change)事件,每个mat-button-toggle的value设为对应路由路径:
<mat-button-toggle-group [value]="currentRoute" aria-label="页面导航" (change)="onToggleChange($event)" > <mat-button-toggle value="page1">Page1</mat-button-toggle> <mat-button-toggle value="page2">Page2</mat-button-toggle> <mat-button-toggle value="page3">Page3</mat-button-toggle> </mat-button-toggle-group>
方法二:用<a>标签包裹mat-button-toggle
这种方式直接借助原生<a>标签的routerLink指令,同时调整样式消除a标签的默认样式,保持按钮组的视觉一致性。
模板代码
<mat-button-toggle-group aria-label="页面导航"> <a routerLink="/page1" style="text-decoration: none; color: inherit;"> <mat-button-toggle [checked]="router.url === '/page1'">Page1</mat-button-toggle> </a> <a routerLink="/page2" style="text-decoration: none; color: inherit;"> <mat-button-toggle [checked]="router.url === '/page2'">Page2</mat-button-toggle> </a> <a routerLink="/page3" style="text-decoration: none; color: inherit;"> <mat-button-toggle [checked]="router.url === '/page3'">Page3</mat-button-toggle> </a> </mat-button-toggle-group>
注意:需要在组件类中将
router实例声明为public(public router: Router),才能在模板中通过router.url判断当前路由,进而设置按钮的checked状态。
总结
两种方法都能满足需求:方法一更贴合Angular Material组件的设计逻辑,状态同步更简洁;方法二实现更直接,适合快速开发。无需完全替换成自定义样式的<a>标签,选一种符合项目习惯的方式即可。
内容的提问来源于stack exchange,提问作者bjmc
相关产品推荐
相关产品推荐

