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

Mic*_*ryl 275 javascript typescript angular2-routing angular

注意: 这里有许多不同的答案,大多数都是有效的.事实是,当Angular团队改变其路由器时,有效的改变了很多次.最终将成为 Angular路由器的Router 3.0版本打破了许多这些解决方案,但它提供了一个非常简单的解决方案.从RC.3开始,首选的解决方案是使用[routerLinkActive]本答案中所示.

在Angular应用程序中(当我写这篇文章时,目前在2.0.0-beta.0版本中),您如何确定当前活动路由是什么?

我正在开发一个使用Bootstrap 4的应用程序,我需要一种方法将导航链接/按钮标记为在<router-output>标记中显示其关联组件时处于活动状态.

我意识到,当点击其中一个按钮时,我可以自己维护状态,但这不会涵盖将多条路径放入同一路径的情况(例如主导航菜单以及主要组件中的本地菜单) ).

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

jes*_*nho 322

使用新的Angular路由器,您可以[routerLinkActive]="['your-class-name']"为所有链接添加属性:

<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>
Run Code Online (Sandbox Code Playgroud)

或者,如果只需要一个类,则为简化的非数组格式:

<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅记录不完整的routerLinkActive指令.(我通常通过反复试验来解决这个问题.)

更新:routerLinkActive现在可以在此处找到更好的指令文档.(感谢@Victor Hugo Arango A.在下面的评论中.)

  • 在给定的示例中,[routerLinkActive]被添加到<a />标记中,但是,如果在其他地方需要该类,它也可以放在其他元素上.<ul> <li [routerLinkActive] ="['active']"> <a [routerLink]="[myRoute.Route]"> (7认同)
  • 当路线的孩子活跃时,有没有办法激活它?代码有一个`@input`用于选项,但只要当前路由的兄弟节点也处于活动状态,`exact:false`就会激活该类. (4认同)
  • 官方文档中的示例可以帮助您:https://angular.io/docs/ts/latest/api/router/index/RouterLinkActive-directive.html (4认同)
  • @jessepinho-尝试过-[routerLinkActive] =“'active'”仅在a-tag中也包含[routerLink]时才有效。如果您使用(click)=“ navitageTo('/ route')”而不是[routerLink],并且在该函数中调用了this.router.navigate(route),则将加载新组件,但您的活动CSS类将不会加载'不适用。我正在尝试在此函数中执行其他操作,除了this.router.navigate(..)。 (2认同)

Ale*_*tos 66

我在另一个问题上回答了这个问题,但我相信它也可能与这个问题有关.以下是原始答案的链接: Angular 2:如何使用参数确定活动路径?

我一直试图设置活动类,而不必确切知道当前位置是什么(使用路由名称).到目前为止,我所使用的最佳解决方案是使用类中可用的函数isRouteActiveRouter.

router.isRouteActive(instruction): Boolean采用一个参数,其是一个路由Instruction对象,并返回truefalse该指令是否成立与否的当前路由.您可以Instruction使用Router' generate(linkParams:Array)生成路由.LinkParams遵循与传递给routerLink指令的值完全相同的格式(例如router.isRouteActive(router.generate(['/User', { user: user.id }]))).

这就是RouteConfig的样子(我已经调整了一下以显示params的用法):

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

是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

到目前为止,这是我首选的问题解决方案,它也可能对您有所帮助.

  • 这可以在rc1中使用:`router.urlTree.contains(router.createUrlTree(['Home']))` (9认同)
  • 不要忘记把`Router`放在类的构造函数中 (5认同)
  • 我在尝试实施解决方案时遇到了一些问题,因此可能对某些问题很有用:http://stackoverflow.com/questions/35882998/angular2-typeerror-cannot-read-property-isrouteactive-of-undefined-in/35883070#35883070 (2认同)
  • 在最新的Angular 2版本中,我在路由器配置对象中使用`name`而不是`as`. (2认同)

Quy*_*ang 35

我解决了在这个链接中遇到的问题,我发现你的问题有一个简单的解决方案.你可以router-link-active在你的风格中使用.

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

  • 我相信这应该是公认的答案.Angular2的路由器会自动为您添加. (2认同)
  • 不幸的是,该课程添加<a>,而不是<li> (2认同)

tom*_*bak 32

基于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));
  }
} 
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 这些方法在 Angular 8 中不存在 (2认同)

Jas*_*itz 30

您可以通过将Location对象注入控制器并检查path(),检查当前路由,如下所示:

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

    ...  location.path(); ...
}
Run Code Online (Sandbox Code Playgroud)

您必须首先确保导入它:

import {Location} from "angular2/router";
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用正则表达式与返回的路径进行匹配,以查看哪条路由处于活动状态.请注意,Location无论LocationStrategy您使用哪个类,该类都会返回一个规范化路径.因此,即使您正在使用HashLocationStragegy返回的路径仍然不是形式/foo/bar #/foo/bar


Ank*_*ngh 17

你如何确定当前活跃的路线是什么?

更新:根据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
}
Run Code Online (Sandbox Code Playgroud)

看更多...


Gün*_*uer 13

routerLinkActive可以使用标记活动路线

<a [routerLink]="/user" routerLinkActive="some class list">User</a>
Run Code Online (Sandbox Code Playgroud)

这也适用于其他元素

<div routerLinkActive="some class list">
  <a [routerLink]="/user">User</a>
</div>
Run Code Online (Sandbox Code Playgroud)

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

routerLinkActive="some class list" [routerLinkActiveOptions]="{ exact: false }"
Run Code Online (Sandbox Code Playgroud)

据我所知exact: false,它将成为RC.4的默认值


Kur*_*gor 11

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

Run Code Online (Sandbox Code Playgroud)


Zai*_*han 11

这对我的活动/非活动路线有帮助:

<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive" [ngClass]="rla.isActive ? 'classIfActive' : 'classIfNotActive'">
</a>
Run Code Online (Sandbox Code Playgroud)

参考号


Art*_*iev 10

现在我正在使用rc.4和bootstrap 4,这个对我来说非常适合:

 <li class="nav-item" routerLinkActive="active" [routerLinkActiveOptions]="{exact:
true}">
    <a class="nav-link" [routerLink]="['']">Home</a>
</li>
Run Code Online (Sandbox Code Playgroud)

这适用于url:/ home


Joh*_*edy 9

从 Angular 8 开始,这有效:

<li routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">
    <a [routerLink]="['/']">Home</a>
</li>
Run Code Online (Sandbox Code Playgroud)

{ exact: true } 确保它与 url 匹配。


小智 7

下面是使用RouteData根据当前路线设置menuBar项的样式的方法:

RouteConfig包含带tab的数据(当前路由):

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

一块布局:

  <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>
Run Code Online (Sandbox Code Playgroud)

类:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)


Lev*_*ler 6

这是在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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)


小智 6

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);
}
Run Code Online (Sandbox Code Playgroud)


tch*_*dze 5

Router在Angular 2 RC中不再定义isRouteActivegenerate方法.

urlTree - 返回当前的url树.

createUrlTree(commands: any[], segment?: RouteSegment) - 将一组命令应用于当前url树并创建一个新的url树.

试试以下

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

注意,routeSegment : RouteSegment必须注入组件的构造函数.


Zze*_*Zze 5

只是以为我会添加一个不使用任何打字稿的示例:

<input type="hidden" [routerLink]="'home'" routerLinkActive #home="routerLinkActive" />
<section *ngIf="home.isActive"></section>
Run Code Online (Sandbox Code Playgroud)

routerLinkActive变量绑定到模板变量,然后根据需要重新使用。不幸的是,唯一需要注意的是,你不能拥有这一切的<section>元素#home需要被解决之前解析器击球<section>


Con*_*ver 5

在最新版本的 Angular 中,您可以简单地执行 check router.isActive(routeNameAsString)。例如,请参阅下面的示例:

\n\n
 <div class="collapse navbar-collapse" id="navbarNav">\n    <ul class="navbar-nav">\n      <li class="nav-item" [class.active] = "router.isActive(\'/dashboard\')">\n        <a class="nav-link" href="#">\xd8\xaf\xd8\xa7\xd8\xb4\xd8\xa8\xd9\x88\xd8\xb1\xd8\xaf <span class="sr-only">(current)</span></a>\n      </li>\n      <li class="nav-item" [class.active] = "router.isActive(route.path)" *ngFor="let route of (routes$ | async)">\n        <a class="nav-link" href="javascript:void(0)" *ngIf="route.childRoutes && route.childRoutes.length > 0"\n          [matMenuTriggerFor]="menu">{{route.name}}</a>\n        <a class="nav-link" href="{{route.path}}"\n          *ngIf="!route.childRoutes || route.childRoutes.length === 0">{{route.name}}</a>\n        <mat-menu #menu="matMenu">\n          <span *ngIf="route.childRoutes && route.childRoutes.length > 0">\n            <a *ngFor="let child of route.childRoutes" class="nav-link" href="{{route.path + child.path}}"\n              mat-menu-item>{{child.name}}</a>\n          </span>\n        </mat-menu>\n      </li>\n    </ul>\n    <span class="navbar-text mr-auto">\n      <small>\xd8\xb3\xd9\x84\xd8\xa7\xd9\x85</small> {{ (currentUser$ | async) ? (currentUser$ | async).firstName : \'\xda\xa9\xd8\xa7\xd8\xb1\xd8\xa8\xd8\xb1\' }}\n      {{ (currentUser$ | async) ? (currentUser$ | async).lastName : \'\xd9\x85\xdb\x8c\xd9\x87\xd9\x85\xd8\xa7\xd9\x86\' }}\n    </span>\n  </div>\n
Run Code Online (Sandbox Code Playgroud)\n\n

并确保您没有忘记在组件中注入路由器。

\n


归档时间:

查看次数:

177869 次

最近记录:

6 年,2 月 前