简体   繁体   English

在 Angular 中,您如何确定活动路线?

[英]In Angular, how do you determine the active route?

NOTE: There are many different answers here, and most have been valid at one time or another.注意:这里有许多不同的答案,并且大多数都曾经有效。 The fact is that what works has changed a number of times as the Angular team has changed its Router.事实是,随着 Angular 团队更改其路由器,有效的方法发生了多次变化。 The Router 3.0 version that will eventually be the router in Angular breaks many of these solutions, but offers a very simple solution of its own.最终将成为Angular 中路由器的 Router 3.0 版本打破了许多这些解决方案,但提供了一个非常简单的解决方案。 As of RC.3, the preferred solution is to use [routerLinkActive] as shown in this answer .从 RC.3 开始,首选解决方案是使用[routerLinkActive] ,如本答案所示。

In an Angular application (current in the 2.0.0-beta.0 release as I write this), how do you determine what the currently active route is?在一个 Angular 应用程序中(在我写这篇文章时是 2.0.0-beta.0 版本中的当前版本),你如何确定当前活动的路由是什么?

I'm working on an app that uses Bootstrap 4 and I need a way to mark navigation links/buttons as active when their associated component is being shown in a <router-output> tag.我正在开发一个使用 Bootstrap 4 的应用程序,当导航链接/按钮显示在<router-output>标签中时,我需要一种方法来将导航链接/按钮标记为活动状态。

I realize that I could maintain the state myself when one of the buttons is clicked upon, but that wouldn't cover the case of having multiple paths into the same route (say a main navigation menu as well as a local menu in the main component).我意识到我可以在单击其中一个按钮时自己保持状态,但这不能涵盖将多个路径进入同一路线的情况(比如主导航菜单以及主组件中的本地菜单) )。

Any suggestions or links would be appreciated.任何建议或链接将不胜感激。 Thanks.谢谢。

With the new Angular router , you can add a [routerLinkActive]="['your-class-name']" attribute to all your links:使用新的Angular 路由器,您可以向所有链接添加[routerLinkActive]="['your-class-name']"属性:

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

Or the simplified non-array format if only one class is needed:如果只需要一个类,或者简化的非数组格式:

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

Or an even simpler format if only one class is needed:如果只需要一个类,或者更简单的格式:

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

See the poorly documented routerLinkActive directive for more info.有关详细信息,请参阅文档routerLinkActive指令 (I mostly figured this out via trial-and-error.) (我主要是通过反复试验来解决这个问题的。)

UPDATE: Better documentation for the routerLinkActive directive can now be found here .更新:现在可以在此处找到更好的routerLinkActive指令文档。 (Thanks to @Victor Hugo Arango A. in the comments below.) (感谢@Victor Hugo Arango A. 在下面的评论中。)

I've replied this in another question but I believe it might be relevant to this one as well.我已经在另一个问题中回答了这个问题,但我相信它也可能与这个问题有关。 Here's a link to the original answer: Angular 2: How to determine active route with parameters?这是原始答案的链接: Angular 2: How to determine active route with parameters?

I've been trying to set the active class without having to know exactly what's the current location (using the route name) .我一直在尝试设置活动类,而不必确切知道当前位置(使用路线名称) The is the best solution I have got to so far is using the function isRouteActive available in the Router class.到目前为止,我得到的最好的解决方案是使用Router类中可用的函数isRouteActive

router.isRouteActive(instruction): Boolean takes one parameter which is a route Instruction object and returns true or false whether that instruction holds true or not for the current route. router.isRouteActive(instruction): Boolean接受一个参数,它是一个路由Instruction对象,无论该指令对当前路由是否为true ,都返回truefalse You can generate a route Instruction by using Router 's generate(linkParams: Array) .您可以使用Routergenerate(linkParams: Array)生成路由Instruction LinkParams follows the exact same format as a value passed into a routerLink directive (eg router.isRouteActive(router.generate(['/User', { user: user.id }])) ). LinkParams 遵循与传递给routerLink指令的值完全相同的格式(例如router.isRouteActive(router.generate(['/User', { user: user.id }])) )。

This is how the RouteConfig could look like (I've tweaked it a bit to show the usage of params) :这就是RouteConfig 的样子(我稍微调整了一下以显示参数的用法)

@RouteConfig([
  { path: '/', component: HomePage, name: 'Home' },
  { path: '/signin', component: SignInPage, name: 'SignIn' },
  { path: '/profile/:username/feed', component: FeedPage, name: 'ProfileFeed' },
])

And the View would look like this:视图将如下所示:

<li [class.active]="router.isRouteActive(router.generate(['/Home']))">
   <a [routerLink]="['/Home']">Home</a>
</li>
<li [class.active]="router.isRouteActive(router.generate(['/SignIn']))">
   <a [routerLink]="['/SignIn']">Sign In</a>
</li>
<li [class.active]="router.isRouteActive(router.generate(['/ProfileFeed', { username: user.username }]))">
    <a [routerLink]="['/ProfileFeed', { username: user.username }]">Feed</a>
</li>

This has been my preferred solution for the problem so far, it might be helpful for you as well.到目前为止,这是我对这个问题的首选解决方案,它可能对您也有帮助。

Small improvement to @alex-correia-santos answer based on https://github.com/angular/angular/pull/6407#issuecomment-190179875对基于https://github.com/angular/angular/pull/6407#issuecomment-190179875 的@alex-correia-santos 答案的小改进

import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
// ...
export class App {
  constructor(private router: Router) {
  }

  // ...

  isActive(instruction: any[]): boolean {
    return this.router.isRouteActive(this.router.generate(instruction));
  }
} 

And use it like this:并像这样使用它:

<ul class="nav navbar-nav">
    <li [class.active]="isActive(['Home'])">
        <a [routerLink]="['Home']">Home</a>
    </li>
    <li [class.active]="isActive(['About'])">
        <a [routerLink]="['About']">About</a>
    </li>
</ul>

I solved a problem I encountered in this link and I find out that there is a simple solution for your question.我解决了我在这个链接中遇到的一个问题,我发现你的问题有一个简单的解决方案。 You could use router-link-active instead in your styles.您可以在您的样式中使用router-link-active

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

You can check the current route by injecting the Location object into your controller and checking the path() , like so:您可以通过将Location对象注入控制器并检查path()来检查当前路线,如下所示:

class MyController {
    constructor(private location:Location) {}

    ...  location.path(); ...
}

You will have to make sure to import it first:您必须确保先导入它:

import {Location} from "angular2/router";

You can then use a regular expression to match against the path that's returned to see which route is active.然后,您可以使用正则表达式匹配返回的路径以查看哪个路由处于活动状态。 Note that the Location class returns a normalized path regardless of which LocationStrategy you're using.请注意,无论您使用的是哪个LocationStrategyLocation类都会返回一个规范化的路径。 So even if you're using the HashLocationStragegy the paths returned will still be of the form /foo/bar not #/foo/bar因此,即使您使用的是HashLocationStragegy ,返回的路径仍将采用/foo/bar的形式,而不是#/foo/bar

To mark active routes routerLinkActive can be used可以使用routerLinkActive来标记活动路由

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

This also works on other elements like这也适用于其他元素,如

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

If partial matches should also be marked use如果部分匹配也应标记使用

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

As far as I know exact: false is going to be the default in RC.4据我所知exact: false将成为 RC.4 中的默认值

how do you determine what the currently active route is?您如何确定当前活动的路线是什么?

UPDATE: updated as per Angular2.4.x更新:根据 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
}

see more... 查看更多...

Right now i'm using rc.4 with bootstrap 4 and this one works perfect for me:现在我正在使用 rc.4 和 bootstrap 4,这个对我来说很完美:

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

This will work for url : /home这将适用于 url :/home

in 2020 if you want to set active class on element which has no [routerLink] - you can do simply:在 2020 年,如果您想在没有 [routerLink] 的元素上设置活动类 - 您可以简单地执行以下操作:

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

As of Angular 8, this works:从 Angular 8 开始,这有效:

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

{ exact: true } ensures it matches the url. { exact: true }确保它与 url 匹配。

Below is the method using RouteData to style menuBar items depending of the current route:下面是使用 RouteData 根据当前路由设置 menuBar 项目样式的方法:

RouteConfig includes data with tab (current route): RouteConfig 包含带有选项卡的数据(当前路由):

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

A piece of layout:一块布局:

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

Class:班级:

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;
  }
}

Just thought I would add in an example which doesn't use any typescript:只是想我会添加一个不使用任何打字稿的例子:

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

The routerLinkActive variable is bound to a template variable and then re-used as required. routerLinkActive变量绑定到模板变量,然后根据需要重新使用。 Unfortunately the only caveat is that you can't have this all on the <section> element as #home needs to be resolved prior to the parser hitting <section> .不幸的是,唯一需要注意的是,您不能将所有这些都放在<section>元素上,因为#home需要在解析器点击<section>之前解析。

Router in Angular 2 RC no longer defines isRouteActive and generate methods. Angular 2 RC 中的Router不再定义isRouteActivegenerate方法。

urlTree - Returns the current url tree. urlTree - 返回当前的 url 树。

createUrlTree(commands: any[], segment?: RouteSegment) - Applies an array of commands to the current url tree and creates a new url tree. createUrlTree(commands: any[], segment?: RouteSegment) - 将命令数组应用于当前 url 树并创建一个新的 url 树。

Try following尝试以下

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

notice, routeSegment : RouteSegment must be injected into component's constructor.注意, routeSegment : RouteSegment必须注入到组件的构造函数中。

Here's a complete example for adding active route styling in Angular version 2.0.0-rc.1 which takes into account null root paths (eg path: '/' )这是在 Angular 版本2.0.0-rc.1添加活动路由样式的完整示例,它考虑了空根路径(例如path: '/'

app.component.ts -> Routes 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应用程序组件.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>

Solution for Angular2 RC 4: Angular2 RC 4 的解决方案:

import {containsTree} from '@angular/router/src/url_tree';
import {Router} from '@angular/router';

export function isRouteActive(router: Router, route: string) {
   const currentUrlTree = router.parseUrl(router.url);
   const routeUrlTree = router.createUrlTree([route]);
   return containsTree(currentUrlTree, routeUrlTree, true);
}

Using routerLinkActive is good in simple cases, when there is a link and you want to apply some classes.在简单的情况下使用routerLinkActive是很好的,当有一个链接并且你想应用一些类时。 But in more complex cases where you may not have a routerLink or where you need something more you can create and use a pipe :但在更复杂的情况下,您可能没有 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);
    }
}

then:然后:

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

and don't forget to include pipe in the pipes dependencies ;)并且不要忘记在管道依赖项中包含管道;)

Another Workaround.另一种解决方法。 Much easier in Angular Router V3 Alpha.在 Angular Router V3 Alpha 中要容易得多。 by injecting Router通过注入路由器

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

export class AppComponent{

    constructor(private router : Router){}

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

usage用法

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

In Angular2 RC2 you can use this simple implementation在 Angular2 RC2 中你可以使用这个简单的实现

<a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>

this will add class active to the element with matched url, read more about it here这会将类active添加到具有匹配 url 的元素中, 在此处阅读有关它的更多信息

Below are the answers to this question for all the versions of Angular 2 RC versions released till date:以下是迄今为止发布的所有 Angular 2 RC 版本的这个问题的答案:

RC4 and RC3 : RC4 和 RC3

For applying class to link or ancestor of link :将类应用于链接或链接的祖先:

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

/home should be the URL and not the name of route since name property no longer exists on Route Object as of Router v3. /home 应该是 URL 而不是路由的名称,因为从路由器 v3 开始,路由对象上不再存在 name 属性。

More about routerLinkActive directive at this link .在此链接中了解有关 routerLinkActive 指令的更多信息。

For applying class to any div based on current route :将类应用于基于当前路由的任何 div :

  • Inject Router into constructor of component.将 Router 注入到组件的构造函数中。
  • User router.url for comparison.用户 router.url 进行比较。

eg例如

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

RC2 and RC1 : RC2 和 RC1

Use combination of router.isRouteActive and class.*.使用 router.isRouteActive 和 class.* 的组合。 eg to apply active class based on Home Route.例如应用基于本地路由的活动类。

Name and url can both be passed into router.generate. Name 和 url 都可以传递到 router.generate 中。

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

For Angular version 4+, you don't need to use any complex solution.对于 Angular 4+ 版本,您不需要使用任何复杂的解决方案。 You can simply use [routerLinkActive]="'is-active'" .您可以简单地使用[routerLinkActive]="'is-active'"

For an example with bootstrap 4 nav link:以 bootstrap 4 导航链接为例:

    <ul class="navbar-nav mr-auto">
      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/home">Home</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/about-us">About Us</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link " routerLink="/contact-us">Contact</a>
      </li>
    </ul>

And in the latest version of angular, you can simply do check router.isActive(routeNameAsString) .在最新版本的 angular 中,您只需检查router.isActive(routeNameAsString) For example see the example below:例如,请参见下面的示例:

 <div class="collapse navbar-collapse" id="navbarNav">
    <ul class="navbar-nav">
      <li class="nav-item" [class.active] = "router.isActive('/dashboard')">
        <a class="nav-link" href="#">داشبورد <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item" [class.active] = "router.isActive(route.path)" *ngFor="let route of (routes$ | async)">
        <a class="nav-link" href="javascript:void(0)" *ngIf="route.childRoutes && route.childRoutes.length > 0"
          [matMenuTriggerFor]="menu">{{route.name}}</a>
        <a class="nav-link" href="{{route.path}}"
          *ngIf="!route.childRoutes || route.childRoutes.length === 0">{{route.name}}</a>
        <mat-menu #menu="matMenu">
          <span *ngIf="route.childRoutes && route.childRoutes.length > 0">
            <a *ngFor="let child of route.childRoutes" class="nav-link" href="{{route.path + child.path}}"
              mat-menu-item>{{child.name}}</a>
          </span>
        </mat-menu>
      </li>
    </ul>
    <span class="navbar-text mr-auto">
      <small>سلام</small> {{ (currentUser$ | async) ? (currentUser$ | async).firstName : 'کاربر' }}
      {{ (currentUser$ | async) ? (currentUser$ | async).lastName : 'میهمان' }}
    </span>
  </div>

And make sure you are not forgetting injecting router in your component.并确保您不会忘记在组件中注入路由器。

An instance of the Router class is actually an Observable and it returns the current path everytime it changes. Router 类的一个实例实际上是一个 Observable 并且每次更改时都会返回当前路径。 This is how I do it :这就是我的做法:

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;
 } 
}

And then in my HTML :然后在我的 HTML 中:

<a [routerLink]="['Contact']" class="item" [class.active]="isCurrentRoute('contact')">Contact</a>

As mentioned in one of the comments of the accepted answer, the routerLinkActive directive can also be applied to a container of the actual <a> tag.如已接受答案的评论之一所述, routerLinkActive指令也可以应用于实际<a>标记的容器。

So for example with Twitter Bootstrap tabs where the active class should be applied to the <li> tag that contains the link :例如,对于 Twitter Bootstrap 选项卡,应将活动类应用于包含链接的<li>标签:

<ul class="nav nav-tabs">
    <li role="presentation" routerLinkActive="active">
        <a routerLink="./location">Location</a>
    </li>
    <li role="presentation" routerLinkActive="active">
        <a routerLink="./execution">Execution</a>
    </li>
</ul>

Pretty neat !漂亮整齐 ! I suppose the directive inspects the content of the tag and looks for an <a> tag with the routerLink directive.我想该指令会检查标签的内容并使用routerLink指令查找<a>标签。

Simple solution for angular 5 users is, just add routerLinkActive to the list item. angular 5 用户的简单解决方案是,只需将routerLinkActive添加到列表项。

A routerLinkActive directive is associated with a route through a routerLink directive. routerLinkActive指令通过routerLink指令与路由相关联。

It takes as input an array of classes which it will add to the element it's attached to if it's route is currently active, like so:它需要一个类数组作为输入,如果它的路由当前处于活动状态,它将添加到它所附加的元素中,如下所示:

<li class="nav-item"
    [routerLinkActive]="['active']">
  <a class="nav-link"
     [routerLink]="['home']">Home
  </a>
</li>

The above will add a class of active to the anchor tag if we are currently viewing the home route.如果我们当前正在查看家庭路线,则上面将向锚标记添加一类活动。

演示

I was seeking a way to use a Twitter Bootstrap style nav with Angular2, but had trouble getting the active class applied to the parent element of the selected link.我正在寻找一种将 Twitter Bootstrap 样式导航与 Angular2 结合使用的方法,但无法将active类应用于所选链接的父元素。 Found that @alex-correia-santos's solution works perfectly!发现@alex-correia-santos 的解决方案非常有效!

The component containing your tabs has to import the router and define it in its constructor before you can make the necessary calls.包含选项卡的组件必须先导入路由器并在其构造函数中定义它,然后才能进行必要的调用。

Here's a simplified version of my implementation...这是我的实现的简化版本......

import {Component} from 'angular2/core';
import {Router, RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
import {HomeComponent} from './home.component';
import {LoginComponent} from './login.component';
import {FeedComponent} from './feed.component';

@Component({
  selector: 'my-app',
  template: `
    <ul class="nav nav-tabs">
      <li [class.active]="_r.isRouteActive(_r.generate(['Home']))">
        <a [routerLink]="['Home']">Home</a>
      </li>
      <li [class.active]="_r.isRouteActive(_r.generate(['Login']))">
        <a [routerLink]="['Login']">Sign In</a>
      </li>
      <li [class.active]="_r.isRouteActive(_r.generate(['Feed']))">
        <a [routerLink]="['Feed']">Feed</a>
      </li>
    </ul>`,
  styleUrls: ['app/app.component.css'],
  directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  { path:'/', component:HomeComponent, name:'Home', useAsDefault:true },
  { path:'/login', component:LoginComponent, name:'Login' },
  { path:'/feed', component:FeedComponent, name:'Feed' }
])
export class AppComponent {
  title = 'My App';
  constructor( private _r:Router ){}
}

let's say you want to add CSS to my active state/tab.假设您想将 CSS 添加到我的活动状态/选项卡中。 Use routerLinkActive to activate your routing link.使用routerLinkActive激活您的路由链接。

note : 'active' is my class name here注意:'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>

A programatic way would be to do it in the component itself.一种编程方式是在组件本身中进行。 I struggled three weeks on this issue, but gave up on angular docs and read the actual code that made routerlinkactive work and Thats about the best docs I can find.我在这个问题上挣扎了三个星期,但放弃了 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
}

Note :注意
For the programatic way, make sure to add the router-link and it takes a child element.对于编程方式,请确保添加路由器链接并且它需要一个子元素。 If you want to change that, you need to get rid of the children on superclass.nativeElement .如果你想改变它,你需要摆脱superclass.nativeElement上的孩子。

This helped me for active/inactive routes:这有助于我进行活动/非活动路线:

<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive" [ngClass]="rla.isActive ? 'classIfActive' : 'classIfNotActive'">
</a>

Ref参考

I'm using angular router ^3.4.7 and I'm still having problems with the routerLinkActive directive.我正在使用 angular router ^3.4.7并且我仍然遇到routerLinkActive指令的问题。

It's not working if you have multiple link with the same url plus it does not seem to refresh all the time.如果您有多个具有相同 url 的链接,并且它似乎不会一直刷新,则它不起作用。

Inspired by @tomaszbak answer I created a little component to do the job受@tomaszbak 回答的启发,我创建了一个小组来完成这项工作

Pure html template be like纯html模板就像

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

NOTE: There are many different answers here, and most have been valid at one time or another.注意:这里有很多不同的答案,大多数答案一次或一次都有效。 The fact is that what works has changed a number of times as the Angular team has changed its Router.事实是,随着Angular团队更改了路由器,有效的更改已经发生了许多次。 The Router 3.0 version that will eventually be the router in Angular breaks many of these solutions, but offers a very simple solution of its own.最终将成为Angular中路由器的Router 3.0版本打破了许多这些解决方案,但提供了自己的非常简单的解决方案。 As of RC.3, the preferred solution is to use [routerLinkActive] as shown in this answer .从RC.3开始,首选解决方案是使用[routerLinkActive] ,如本答案所示。

In an Angular application (current in the 2.0.0-beta.0 release as I write this), how do you determine what the currently active route is?在Angular应用程序中(我撰写本文时为2.0.0-beta.0版本中的当前版本),如何确定当前活动的路由是什么?

I'm working on an app that uses Bootstrap 4 and I need a way to mark navigation links/buttons as active when their associated component is being shown in a <router-output> tag.我正在开发一个使用Bootstrap 4的应用程序,当在<router-output>标记中显示其关联组件时,我需要一种方法来将导航链接/按钮标记为活动状态。

I realize that I could maintain the state myself when one of the buttons is clicked upon, but that wouldn't cover the case of having multiple paths into the same route (say a main navigation menu as well as a local menu in the main component).我意识到,当单击其中一个按钮时,我可以自己维护状态,但这不会涵盖将多条路径放入同一条路线的情况(例如主导航菜单以及主组件中的本地菜单) )。

Any suggestions or links would be appreciated.任何建议或链接将不胜感激。 Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM