注意:这里有许多不同的答案,大多数在某个时期是有效的。事实上,随着Angular团队对路由器的改变,工作原理也发生了多次变化。最终将成为Angular路由器的Router 3.0版本打破了许多这些解决方案,但它提供了一个非常简单的解决方案。从RC.3开始,首选的解决方案是使用[routerLinkActive],如下所示。

在Angular应用程序中(当前在2.0.0 beta版中)。当我写这篇文章时,0发布),你如何确定当前活动的路由是什么?

我正在开发一个使用Bootstrap 4的应用程序,我需要一种方法来标记导航链接/按钮为活动时,他们的相关组件显示在<router-output>标签。

我意识到,当单击其中一个按钮时,我可以自己维护状态,但这不能涵盖进入同一路由的多条路径的情况(比如主导航菜单和主组件中的本地菜单)。

任何建议或链接将不胜感激。谢谢。


当前回答

Angular 2 RC中的路由器不再定义isRouteActive和generate方法。

urlTree -返回当前的url树。 createUrlTree(命令:any[], segment?: routessegment) -应用命令数组到当前url树并创建一个新的url树。

尝试后

<li 
[class.active]=
"router.urlTree.contains(router.createUrlTree(['/SignIn', this.routeSegment]))">

注意,routessegment: routessegment必须注入到组件的构造函数中。

其他回答

另一个解决方案。在Angular Router V3 Alpha中要简单得多。注入路由器

import {Router} from "@angular/router";

export class AppComponent{

    constructor(private router : Router){}

    routeIsActive(routePath: string) {
        return this.router.url == routePath;
    }
}

使用

<div *ngIf="routeIsActive('/')"> My content </div>

首先在.ts中导入RouterLinkActive

import {RouterLinkActive} from '@angular/router';

现在在HTML中使用RouterLinkActive

<span class="" routerLink ="/some_path" routerLinkActive="class_Name">Value</span></a>

为类“class_Name”提供一些css,因为当这个链接被激活/单击时,你会在span检查时发现这个类。

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>

如何确定当前活动的路由是什么?

更新:根据Angular2.4.x更新

constructor(route: ActivatedRoute) {
   route.snapshot.params; // active route's params

   route.snapshot.data; // active route's resolved data

   route.snapshot.component; // active route's component

   route.snapshot.queryParams // The query parameters shared by all the routes
}

查看更多

在2020年,如果你想在没有[routerLink]的元素上设置active类,你可以简单地做:

<a
  (click)="bookmarks()"
  [class.active]="router.isActive('/string/path/'+you+'/need', false)" // <== you need this one. second argument 'false' - exact: true/false
  routerLinkActive="active"
  [routerLinkActiveOptions]="{ exact: true }"
>
  bookmarks
</a>