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

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

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

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

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


当前回答

我使用的是angular路由器^3.4.7,我仍然有routerLinkActive指令的问题。

这是不工作,如果你有多个链接与相同的url加上它似乎不刷新所有的时间。

受到@tomaszbak答案的启发,我创建了一个小组件来完成这项工作

其他回答

让我们说你想添加CSS到我的active state/标签。使用routerLinkActive激活路由链路。

注意:'active'是我的类名

<style>
   .active{
       color:blue;
     }
</style>

  <a routerLink="/home" [routerLinkActive]="['active']">Home</a>
  <a routerLink="/about" [routerLinkActive]="['active']">About</a>
  <a routerLink="/contact" [routerLinkActive]="['active']">Contact</a>

另一个解决方案。在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>

要标记活动路由,可以使用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中的默认值

在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>

一种程序化的方式是在组件本身中完成。我在这个问题上挣扎了三周,但最终放弃了angular文档,转而阅读了让routerlinkactive工作的实际代码,这是我能找到的最好的文档了。

    import {
  Component,AfterContentInit,OnDestroy, ViewChild,OnInit, ViewChildren, AfterViewInit, ElementRef, Renderer2, QueryList,NgZone,ApplicationRef
}
  from '@angular/core';
  import { Location } from '@angular/common';

import { Subscription } from 'rxjs';
import {
  ActivatedRoute,ResolveStart,Event, Router,RouterEvent, NavigationEnd, UrlSegment
} from '@angular/router';
import { Observable } from "rxjs";
import * as $ from 'jquery';
import { pairwise, map } from 'rxjs/operators';
import { filter } from 'rxjs/operators';
import {PageHandleService} from '../pageHandling.service'
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})




export class HeaderComponent implements AfterContentInit,AfterViewInit,OnInit,OnDestroy{

    public previousUrl: any;
    private subscription: Subscription;


      @ViewChild("superclass", { static: false } as any) superclass: ElementRef;
      @ViewChildren("megaclass") megaclass: QueryList<ElementRef>;


  constructor( private element: ElementRef, private renderer: Renderer2, private router: Router, private activatedRoute: ActivatedRoute, private location: Location, private pageHandleService: PageHandleService){
    this.subscription = router.events.subscribe((s: Event) => {
      if (s instanceof NavigationEnd) {
        this.update();
      }
    });


  }


  ngOnInit(){

  }


  ngAfterViewInit() {
  }

  ngAfterContentInit(){
  }



private update(): void {
  if (!this.router.navigated || !this.superclass) return;
      Promise.resolve().then(() => {
        this.previousUrl = this.router.url

        this.megaclass.toArray().forEach( (superclass) => {

          var superclass = superclass
          console.log( superclass.nativeElement.children[0].classList )
          console.log( superclass.nativeElement.children )

          if (this.previousUrl == superclass.nativeElement.getAttribute("routerLink")) {
            this.renderer.addClass(superclass.nativeElement.children[0], "box")
            console.log("add class")

          } else {
            this.renderer.removeClass(superclass.nativeElement.children[0], "box")
            console.log("remove class")
          }

        });
})
//update is done
}
ngOnDestroy(): void { this.subscription.unsubscribe(); }


//class is done
}

注意: 对于编程方式,请确保添加router-link,并且它接受一个子元素。如果你想要改变它,你需要在superclass.nativeElement上去掉子元素。