You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 6 Material:mat-tab-link选中态下划线无法跟随切换问题

解决mat-tab-nav-bar下划线不跟随激活按钮的问题

这个问题我太熟悉了——核心原因是Angular的routerLinkActive默认采用部分匹配策略,而你的第一个路由是空路径'',所有其他路由的URL(比如/the-solution)都会包含这个空前缀,所以第一个链接的rla.isActive永远为true,导致下划线一直固定在第一个按钮位置,即使你跳转到其他页面也不会改变。

下面给你两种可行的解决方案:

方案一:修改路由配置,添加pathMatch: 'full'

在路由配置中给空路径的路由加上pathMatch: 'full',这样只有当URL完全匹配空字符串(也就是首页)时,这个路由才会被标记为激活状态。

修改后的app-routing.module.ts代码:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { TheProblemComponent } from './the-problem/the-problem.component';
import { TheSolutionComponent } from './the-solution/the-solution.component';
import { TheGameComponent } from './the-game/the-game.component';
import { ProbabilityCalculatorComponent } from './probability-calculator/probability-calculator.component';

const routes: Routes = [
  { path: '', component: TheProblemComponent, pathMatch: 'full' }, // 添加pathMatch: 'full'
  { path: 'the-solution', component: TheSolutionComponent },
  { path: 'the-game', component: TheGameComponent },
  { path: 'probability-calculator', component: ProbabilityCalculatorComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule { }

方案二:给routerLinkActive添加精确匹配选项

如果你不想修改路由配置,也可以在mat-tab-link上给routerLinkActive添加精确匹配选项,强制该链接只有在URL完全匹配时才激活。

修改后的app.component.html代码:

<nav mat-tab-nav-bar>
  <a mat-tab-link 
     *ngFor="let link of navLinks" 
     [routerLink]="link.path" 
     routerLinkActive 
     #rla="routerLinkActive"
     [routerLinkActiveOptions]="{ exact: true }" <!-- 添加精确匹配选项 -->
     [active]="rla.isActive">
    {{link.label}}
  </a>
</nav>
<router-outlet></router-outlet>

效果验证

两种方案都能完美解决你的问题:

  • 第一个链接现在只会在你处于首页(空路径)时才会被标记为激活状态
  • 当你跳转到其他页面时,对应的mat-tab-link会正确激活,蓝色下划线也会跟随到当前激活的按钮上
  • 按钮的背景色切换和页面跳转功能依然保持正常

内容的提问来源于stack exchange,提问作者Marcus Edensky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:22:09