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

Router Link Active不生效,如何动态添加类激活按钮?

问题原因

routerLinkActive指令是专门配合routerLink使用的,它的作用是匹配当前路由路径,给对应的元素添加激活类。但你的场景里,按钮只是触发点击事件执行方法,并没有通过routerLink导航路由,所以这个指令自然不会生效。

解决方案:用变量跟踪激活状态

我们可以通过定义一个组件变量来跟踪当前选中的视图,然后用Angular的属性绑定动态添加active类,步骤如下:

  1. 在组件TS中添加状态变量
    定义一个currentView变量,用来记录当前激活的视图类型,默认可以设为第一个按钮对应的'branch':
// 组件TS代码
currentView: string = 'branch'; // 默认激活"By branch"按钮

setView(view: string) {
  this.currentView = view; // 更新当前激活视图
  // 你的其他逻辑...
}

// 保留原有的get方法
getFranchiseRefillsByDateAndBranch() {
  this.items = [];
  var hrchyIds = this.jwtHelperService.getFRefillHrchyIds();
  var ym = this.localStorage.retrieve('frym');
  if (hrchyIds) {
    this.refillService.getFranchiseRefillsByDateAndYear(hrchyIds, ym, "branch", this.page, this.rec).subscribe(val => {
      this.items = val;
    });
  }
}
  1. 修改HTML,绑定动态类
    给每个li元素添加[class.active]属性绑定,判断currentView是否等于当前按钮对应的视图值:
<div class="card-header">
  <h5>Refill by date</h5>
  <div class="card-header-right">
    <nav class="navbar bg-faded ">
      <ul class="nav navbar-nav">
        <li class="nav-item" [class.active]="currentView === 'branch'">
          <button (click)="setView('branch'); getFranchiseRefillsByDateAndBranch()" class="btn btn-mini btn-bg-c-blue btn-outline-default btn-round btn-action">
            <i class="icofont icofont-ui-check"> By branch</i>
          </button>
        </li>
        <li class="nav-item" [class.active]="currentView === 'product'">
          <button (click)="setView('product'); getFranchiseRefillsByDateAndProduct()" class="btn btn-mini btn-bg-c-blue btn-outline-default btn-round btn-action">
            <i class="icofont icofont-ui-check"> By product</i>
          </button>
        </li>
        <li class="nav-item" [class.active]="currentView === 'list'">
          <button (click)="setView('list'); getFranchiseRefillsByDateAndList()" class="btn btn-mini btn-bg-c-blue btn-outline-default btn-round btn-action">
            <i class="icofont icofont-ui-check"> Refill list</i>
          </button>
        </li>
      </ul>
    </nav>
  </div>
</div>
  1. CSS样式保持不变
    你原来的CSS可以继续使用,它会选中激活状态下按钮内的i元素:
.nav-item.active button i{
  color: #3D94CD !important;
}

原理说明

通过currentView变量维护当前激活的视图类型,每次点击按钮时,调用setView更新这个变量,Angular会自动检测变量变化,动态给对应的li添加或移除active类,从而实现你想要的颜色切换效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:19:15