问题的原因在于routerLinkActive指令仅在路由链接激活时更新,因此需要单击其他位置以触发更新。为避免这种情况,添加一个主题观察者,以便在路由更改时手动调用此指令的更新方法。
在组件的ts文件中添加以下代码:
import { Component, OnInit } from '@angular/core'; import { NavigationEnd, Router } from '@angular/router';
@Component({ selector: 'app-component', templateUrl: './component.html', styleUrls: ['./component.scss'] }) export class Component implements OnInit {
constructor(private router: Router) { }
ngOnInit() { this.router.events.subscribe((event) => { if (event instanceof NavigationEnd) { // 使用 setTimeout 异步执行以避免出现 ExpressionChangedAfterItHasBeenCheckedError。 setTimeout(() => { this.router.routeReuseStrategy.shouldReuseRoute = () => false; }); } }); } }
此示例中,我们订阅了路由器事件,使用 NavigationEnd 事件来检测路由更改。当路由更改时,我们异步地重写路由复用策略,强制更新组件并触发routerLinkActive的更新。
在组件HTML模板中使用routerLinkActive,如下所示:
在每个需要使用routerLinkActive的链接上添加routerLinkActive属性及其相应的激活CSS类名。当路由为活动状态时,会自动添加该CSS类。
通过将上述代码添加到组件中,您现在应该能够解决Angular routerLinkActive仅在单击屏幕其他位置后更新的问题。