注意:这里有许多不同的答案,大多数在某个时期是有效的。事实上,随着Angular团队对路由器的改变,工作原理也发生了多次变化。最终将成为Angular路由器的Router 3.0版本打破了许多这些解决方案,但它提供了一个非常简单的解决方案。从RC.3开始,首选的解决方案是使用[routerLinkActive],如下所示。
在Angular应用程序中(当前在2.0.0 beta版中)。当我写这篇文章时,0发布),你如何确定当前活动的路由是什么?
我正在开发一个使用Bootstrap 4的应用程序,我需要一种方法来标记导航链接/按钮为活动时,他们的相关组件显示在<router-output>标签。
我意识到,当单击其中一个按钮时,我可以自己维护状态,但这不能涵盖进入同一路由的多条路径的情况(比如主导航菜单和主组件中的本地菜单)。
任何建议或链接将不胜感激。谢谢。
你可以通过将Location对象注入控制器并检查path()来检查当前路由,如下所示:
class MyController {
constructor(private location:Location) {}
... location.path(); ...
}
你必须确保首先导入它:
import {Location} from "angular2/router";
然后,您可以使用正则表达式与返回的路径进行匹配,以查看哪个路由是活动的。注意,Location类返回一个规范化的路径,而不管您使用的是哪个LocationStrategy。所以即使你在使用hashlocationstrategy,返回的路径仍然是/foo/bar的形式,而不是#/foo/bar
Router类的实例实际上是一个可观察对象,它每次改变时都会返回当前路径。我是这样做的:
export class AppComponent implements OnInit {
currentUrl : string;
constructor(private _router : Router){
this.currentUrl = ''
}
ngOnInit() {
this._router.subscribe(
currentUrl => this.currentUrl = currentUrl,
error => console.log(error)
);
}
isCurrentRoute(route : string) : boolean {
return this.currentUrl === route;
}
}
然后在我的HTML中
<a [routerLink]="['Contact']" class="item" [class.active]="isCurrentRoute('contact')">Contact</a>