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

Angular中菜单选项选中时高亮对应工具栏按钮的问题

解决Mat菜单选项选中后高亮对应工具栏按钮的问题

直接给工具栏按钮添加routerLink和routerLinkActive会导致未点击菜单选项时也高亮,原因是routerLinkActive会自动匹配当前路由与按钮的routerLink是否匹配(即使你不需要点击按钮跳转)。我们可以通过监听路由变化,手动控制按钮的高亮状态来解决这个问题:

步骤1:修改模板结构

移除工具栏按钮上的routerLink和routerLinkActive,改用动态绑定类的方式:

<!-- 工具栏按钮 -->
<button mat-button 
        [matMenuTriggerFor]="employeeMenu" 
        [class.active]="isEmployeeRouteActive">
  Employee
</button>

<!-- 员工菜单 -->
<mat-menu #employeeMenu="matMenu">
  <a mat-menu-item routerLink="/employee/list">List</a>
  <a mat-menu-item routerLink="/employee/add">Add Employee</a>
</mat-menu>

步骤2:组件内监听路由变化

在组件类中注入Router服务,监听路由导航结束事件,判断当前路由是否属于员工相关路径:

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'app-toolbar',
  templateUrl: './toolbar.component.html',
  styleUrls: ['./toolbar.component.css']
})
export class ToolbarComponent implements OnInit {
  isEmployeeRouteActive = false;
  // 定义需要触发高亮的员工相关路由
  private readonly employeeTargetRoutes = ['/employee/list', '/employee/add'];

  constructor(private router: Router) {}

  ngOnInit(): void {
    this.router.events.pipe(
      // 只监听导航完成的事件
      filter(event => event instanceof NavigationEnd)
    ).subscribe((event: NavigationEnd) => {
      // 判断当前路由是否在目标列表中
      this.isEmployeeRouteActive = this.employeeTargetRoutes.includes(event.urlAfterRedirects);
    });
  }
}

步骤3:添加高亮样式

在组件的CSS文件中定义active类的高亮样式:

.active {
  background-color: rgba(25, 118, 210, 0.1);
  color: #1976d2;
  /* 可根据需求自定义其他样式,比如边框、阴影等 */
}

替代方案(基于CSS关联)

如果不想写组件逻辑,也可以利用routerLinkActive在菜单容器上的匹配结果,通过CSS选择器关联工具栏按钮(依赖DOM结构相邻):

<div class="toolbar-item">
  <button mat-button [matMenuTriggerFor]="employeeMenu">Employee</button>
  <mat-menu #employeeMenu="matMenu">
    <div routerLinkActive="menu-active" [routerLinkActiveOptions]="{exact: false}">
      <a mat-menu-item routerLink="/employee/list">List</a>
      <a mat-menu-item routerLink="/employee/add">Add Employee</a>
    </div>
  </mat-menu>
</div>
/* 当菜单内路由激活时,高亮相邻的工具栏按钮 */
.menu-active ~ button {
  background-color: rgba(25, 118, 210, 0.1);
  color: #1976d2;
}

第一种方案更灵活可控,不受DOM结构限制;第二种方案适合简单场景,无需编写额外逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 15:32:41