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

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

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

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

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


当前回答

我只是想添加一个不使用任何typescript的例子:

<input type="hidden" [routerLink]="'home'" routerLinkActive #home="routerLinkActive" />
<section *ngIf="home.isActive"></section>

routerLinkActive变量被绑定到一个模板变量上,然后根据需要重新使用。不幸的是,唯一需要注意的是,您不能将这些都放在<section>元素上,因为#home需要在解析器命中<section>之前解析。

其他回答

在简单的情况下,当有一个链接并且你想应用一些类时,使用routerLinkActive是很好的。但在更复杂的情况下,你可能没有routerLink,或者你需要更多的东西,你可以创建并使用管道:

@Pipe({
    name: "isRouteActive",
    pure: false
})
export class IsRouteActivePipe implements PipeTransform {

    constructor(private router: Router,
                private activatedRoute: ActivatedRoute) {
    }

    transform(route: any[], options?: { queryParams?: any[], fragment?: any, exact?: boolean }) {
        if (!options) options = {};
        if (options.exact === undefined) options.exact = true;

        const currentUrlTree = this.router.parseUrl(this.router.url);
        const urlTree = this.router.createUrlTree(route, {
            relativeTo: this.activatedRoute,
            queryParams: options.queryParams,
            fragment: options.fragment
        });
        return containsTree(currentUrlTree, urlTree, options.exact);
    }
}

然后:

<div *ngIf="['/some-route'] | isRouteActive">...</div>

不要忘记在管道依赖项中包含管道;)

下面是在Angular 2.0.0-rc版本中添加活动路由样式的完整示例。1,它考虑了空根路径(例如path: '/')

app.component.ts ->路由

import { Component, OnInit } from '@angular/core';
import { Routes, Router, ROUTER_DIRECTIVES } from '@angular/router';
import { LoginPage, AddCandidatePage } from './export';
import {UserService} from './SERVICES/user.service';

@Component({
  moduleId: 'app/',
  selector: 'my-app',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.css'],
  providers: [UserService],
  directives: [ROUTER_DIRECTIVES]
})

@Routes([
  { path: '/', component: AddCandidatePage },
  { path: 'Login', component: LoginPage }
])
export class AppComponent  { //implements OnInit

  constructor(private router: Router){}

  routeIsActive(routePath: string) {
     let currentRoute = this.router.urlTree.firstChild(this.router.urlTree.root);
     // e.g. 'Login' or null if route is '/'
     let segment = currentRoute == null ? '/' : currentRoute.segment;
     return  segment == routePath;
  }
}

app.component.html

<ul>
  <li [class.active]="routeIsActive('Login')"><a [routerLink]="['Login']" >Login</a></li>
  <li [class.active]="routeIsActive('/')"><a [routerLink]="['/']" >AddCandidate</a></li>
</ul>
<route-outlet></router-outlet>

首先在.ts中导入RouterLinkActive

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

现在在HTML中使用RouterLinkActive

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

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

以下是迄今为止发布的所有Angular 2 RC版本对这个问题的答案:

RC4和RC3:

将类应用到link或link的祖先:

<li routerLinkActive="active"><a [routerLink]="['/home']">Home</a></li>

/home应该是URL,而不是路由的名称,因为name属性在路由器v3不再存在于路由对象中。

更多关于routerLinkActive指令的信息。

基于当前路由将class应用到任何div:

将路由器注入组件的构造函数。 用户路由器。Url进行比较。

e.g

<nav [class.transparent]="router.url==('/home')">
</nav>

RC2和RC1:

使用路由器组合。isRouteActive和class.*。例如,基于Home Route应用活动类。

Name和url都可以传递到router.generate中。

 <li [class.active]="router.isRouteActive(router.generate(['Home']))">
    <a [routerLink]="['Home']" >Home</a>
</li>

现在我正在使用rc。4与bootstrap 4和这个对我来说是完美的:

 <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact:
true}">
    <a class="nav-link" [routerLink]="['']">Home</a>
</li>

这将适用于url: /home