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

Angular Material中mat-list-item与routerLinkActive激活异常问题

问题原因及解决方案

这个问题的核心是mat-list-item组件自带Material Design的焦点与激活状态逻辑——当侧边栏重新打开时,第一个mat-list-item会自动获取焦点,Material的默认样式会把这种焦点状态渲染成类似激活的视觉效果,而普通div没有这套内置行为,所以routerLinkActive的样式能正常生效。

以下是几种有效的解决办法:

1. 阻止自动获取焦点

给mat-list-item添加tabindex="-1"属性,让它不会在侧边栏打开时自动获得焦点,避免默认样式干扰:

<mat-list-item 
    *ngFor="let menuItem of menuItems"
    [routerLink]="[menuItem.path]"
    routerLinkActive="router-active"
    tabindex="-1"
    (click)="windowInnerWidth < 1200 ? sidenav.close() : null">
    <span matListItemTitle>{{menuItem.title}}</span>
</mat-list-item>

2. 精确匹配路由激活状态

给routerLinkActive添加精确匹配配置,确保只有当路由完全匹配时才添加激活类,避免前缀匹配导致的错误激活:

<mat-list-item 
    *ngFor="let menuItem of menuItems"
    [routerLink]="[menuItem.path]"
    routerLinkActive="router-active"
    [routerLinkActiveOptions]="{exact: true}"
    (click)="windowInnerWidth < 1200 ? sidenav.close() : null">
    <span matListItemTitle>{{menuItem.title}}</span>
</mat-list-item>

3. 覆盖Material默认样式

如果前两种方法效果不佳,可以通过CSS直接覆盖mat-list-item的默认激活/焦点样式,只保留router-active类的红色效果:

/* 清除未匹配路由时的默认激活/焦点样式 */
mat-list-item.mat-mdc-list-item-active:not(.router-active),
mat-list-item:focus:not(.router-active) {
    color: rgba(0, 0, 0, 0.87); /* 匹配Material默认文字颜色 */
    background-color: transparent;
}

/* 保留自定义激活样式 */
.router-active {
    color: red;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:52:45