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

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

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

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

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


当前回答

下面是使用RouteData根据当前路由样式化菜单栏项的方法:

routecconfig包含了tab(当前路由)的数据:

@RouteConfig([
  {
    path: '/home',    name: 'Home',    component: HomeComponent,
    data: {activeTab: 'home'},  useAsDefault: true
  }, {
    path: '/jobs',    name: 'Jobs',    data: {activeTab: 'jobs'},
    component: JobsComponent
  }
])

一份布局:

  <li role="presentation" [ngClass]="{active: isActive('home')}">
    <a [routerLink]="['Home']">Home</a>
  </li>
  <li role="presentation" [ngClass]="{active: isActive('jobs')}">
    <a [routerLink]="['Jobs']">Jobs</a>
  </li>

类:

export class MainMenuComponent {
  router: Router;

  constructor(data: Router) {
    this.router = data;
  }

  isActive(tab): boolean {
    if (this.router.currentInstruction && this.router.currentInstruction.component.routeData) {
      return tab == this.router.currentInstruction.component.routeData.data['activeTab'];
    }
    return false;
  }
}

其他回答

我解决了在这个环节遇到的一个问题,我发现你的问题有一个简单的解决方案。你可以在样式中使用router-link-active。

@Component({
   styles: [`.router-link-active { background-color: red; }`]
})
export class NavComponent {
}

要标记活动路由,可以使用routerLinkActive

<a [routerLink]="/user" routerLinkActive="some class list">User</a>

这也适用于其他元素,如

<div routerLinkActive="some class list">
  <a [routerLink]="/user">User</a>
</div>

如果部分匹配也应标记使用

routerLinkActive="some class list" [routerLinkActiveOptions]="{ exact: false }"

据我所知,exact: false将是RC.4中的默认值

在简单的情况下,当有一个链接并且你想应用一些类时,使用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>

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

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

更新:根据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
}

查看更多

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必须注入到组件的构造函数中。