在Angular中,如何检查相对路由是否激活?

In Angular, how to check the route is active for a relative route?

我导航到组件代码中相对于当前路由的路由,就像在这个代码片段中一样。

this.router.navigate([item.route], {relativeTo: this.route});

如何检查当前路线是否在 HTML 中处于活动状态以应用突出显示样式。目前我正在使用以下内容,但它不适用于相对路线。

<a [ngClass]="{'active': item.route ? router.isActive(item.route, true): false">
{{item.displayName}}
</a> 

这就是我让它工作的方式。如果有更好的解决办法欢迎大家交流

<a [ngClass]="{'active': item.route 
? router.isActive(router.createUrlTree([item.route], {relativeTo: route}).toString(), true) 
: false">
{{item.displayName}}
</a> 

您可以像这样将函数放入您的组件中:

isActive(): boolean {
    return router.isActive(router.createUrlTree([item.route], {relativeTo: route}).toString(), true);
  }

然后在你的模板中你可以这样写:

<a [ngClass]="{'active': isActive() }">{{item.displayName}}</a>