Router link应该基于子路由激活



我有一个设置,我希望路由器链接对'/heroes '也对'/:id/heroes '激活。有什么方法可以为客户端和服务器端渲染做到这一点?

你的路由没有反映任何父子关系。修改为"/heros"one_answers"/heros/:id"。然后routerLinkActive将被激活链接到/heros时,你在/heros/123默认(当routerLinkActiveOptions.exact不为真)。

如果你不能改变你的路由结构,把routerLinkActive换成自定义的东西。例如,在服务中保留一个布尔值的BehaviorSubject,用于标记链接何时应该具有活动类,并在进入其中任何一个路由时将其设置为true,在离开路由时将其设置为false:

// heroes.service.ts
heroesActive$ = new BehaviorSubject(false);
// heroes.component.ts and hero.component.ts
constructor(private heroes:HeroesService) {}
ngOnInit(): void {
this.heroes.heroesActive$.next(true);
}
ngOnDestroy(): void {
this.heroes.heroesActive$.next(false);
}
// menu.component.ts
constructor(public heroes: HeroesService) { }
// menu.component.html
<a [class.active]="heroes.heroesActive$ | async" routerLink="/heroes">/heroes</a>

最新更新