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

Angular 7:ngClass仅生效初始值,路由导航后类不更新求助

Fixing ngClass Not Updating After Route Navigation in Angular

I've dealt with this exact scenario before, so let's walk through why your isActive class isn't updating, plus a few solid solutions to get it working as expected.

The Root Cause

Your isActive method checks this.router.url, but when the route changes, Angular's change detection doesn't automatically trigger a re-evaluation of that method. Since router.url is a plain string (not an observable or a property that triggers change detection), Angular has no clue it needs to update the view after navigation.


Angular has a purpose-built directive for exactly this use case—RouterLinkActive—which automatically handles adding/removing active classes when routes change. It's cleaner, less error-prone, and requires zero custom logic.

Update your template like this:

<div class="dropdown" *ngFor="let item of menu">
  <!-- If your icon is wrapped in a link -->
  <a [routerLink]="item.url" routerLinkActive="isActive">
    <i></i>
    <!-- Your other dropdown content -->
  </a>
</div>

If your icon needs to be standalone (not inside an <a> tag), you can still apply the directive directly to it:

<div class="dropdown" *ngFor="let item of menu">
  <i [routerLink]="item.url" routerLinkActive="isActive"></i>
  <!-- Your other dropdown content -->
</div>

This directive will automatically toggle the isActive class whenever the route matches item.url—no need for your custom isActive method at all!


Solution 2: Trigger Change Detection Manually on Route Events

If you want to keep your custom isActive logic, you can subscribe to route navigation events and tell Angular to re-check the component's view when navigation finishes.

First, update your component code:

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

@Component({
  // Your component metadata here
})
export class YourSideNavComponent implements OnInit {
  constructor(
    private router: Router,
    private cdr: ChangeDetectorRef
  ) {}

  ngOnInit(): void {
    // Listen for when navigation completes
    this.router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe(() => {
      // Tell Angular to update the view
      this.cdr.markForCheck();
    });
  }

  public isActive(item: SideNavMainItem): boolean {
    return this.router.url.indexOf(item.url) !== -1;
  }
}

The markForCheck() method tells Angular's change detector that this component needs to be re-evaluated, which will re-run your isActive method and update the ngClass state.


Solution 3: Use an Observable with the Async Pipe

Another approach is to turn the current route URL into an observable, then use Angular's async pipe in the template. This way, Angular automatically detects when the URL changes and updates the view.

Component code:

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

@Component({
  // Your component metadata here
})
export class YourSideNavComponent {
  // Observable that emits the current URL after navigation ends
  currentUrl$ = this.router.events.pipe(
    filter(event => event instanceof NavigationEnd),
    map(() => this.router.url)
  );

  constructor(private router: Router) {}

  public isActive(item: SideNavMainItem, currentUrl: string): boolean {
    return currentUrl.indexOf(item.url) !== -1;
  }
}

Template update:

<div class="dropdown" *ngFor="let item of menu">
  <i [ngClass]="{'isActive': isActive(item, currentUrl$ | async)}"></i>
  <!-- Your other dropdown content -->
</div>

The async pipe handles subscribing/unsubscribing to the observable, and triggers change detection whenever a new value is emitted.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:29:27