在Angular中,如何确定活动路由?
In Angular, how do you determine the active route?
注意: 这里有许多不同的答案,而且大多数都曾经有效。事实上,随着 Angular 团队更改其路由器,有效的方法已经更改了很多次。最终将成为 中 Angular 路由器的 Router 3.0 版本打破了许多这些解决方案,但提供了一个非常简单的解决方案。从 RC.3 开始,首选解决方案是使用 [routerLinkActive]
,如 .
所示
在 Angular 应用程序中(在我写这篇文章时,当前版本为 2.0.0-beta.0),您如何确定当前活动的路由是什么?
我正在开发一个使用 Bootstrap 4 的应用程序,我需要一种方法来将导航 links/buttons 标记为活动,当它们的关联组件显示在 <router-output>
标记中时.
我意识到当其中一个按钮被点击时我可以自己保持状态,但这不包括有多个路径进入同一路线的情况(比如主导航菜单和本地菜单)主组件中的菜单)。
如有任何建议或链接,我们将不胜感激。谢谢
您可以通过将 Location
对象注入控制器并检查 path()
来检查当前路由,如下所示:
class MyController {
constructor(private location:Location) {}
... location.path(); ...
}
您必须确保首先导入它:
import {Location} from "angular2/router";
然后您可以使用正则表达式匹配返回的路径以查看哪个路由处于活动状态。请注意,Location
class returns 是规范化路径,无论您使用的是哪个 LocationStrategy
。因此,即使您使用 HashLocationStragegy
,返回的路径仍将采用 /foo/bar
not #/foo/bar
的形式
我已经在另一个问题中回答了这个问题,但我相信它也可能与这个问题相关。这是原始答案的 link:
我一直在尝试设置 active class 而不必确切知道当前位置 (使用路线名称)。到目前为止,我得到的最佳解决方案是使用 Router
class.
中可用的函数 isRouteActive
router.isRouteActive(instruction): Boolean
接受一个参数,它是一个路由 Instruction
对象和 returns true
或 false
该指令是否适用于当前路线。您可以使用 Router
的 generate(linkParams: Array). LinkParams follows the exact same format as a value passed into a routerLink 指令(例如 router.isRouteActive(router.generate(['/User', { user: user.id }]))
)生成路由 Instruction
。
这就是 RouteConfig 的样子 (我稍微调整了一下以显示参数的用法):
@RouteConfig([
{ path: '/', component: HomePage, name: 'Home' },
{ path: '/signin', component: SignInPage, name: 'SignIn' },
{ path: '/profile/:username/feed', component: FeedPage, name: 'ProfileFeed' },
])
View 看起来像这样:
<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>
到目前为止,这是我首选的问题解决方案,可能对您也有帮助。
我解决了我在这个 中遇到的一个问题,我发现有一个简单的解决方案可以解决您的问题。您可以在样式中使用 router-link-active
。
@Component({
styles: [`.router-link-active { background-color: red; }`]
})
export class NavComponent {
}
基于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));
}
}
并像这样使用它:
<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>
我正在寻找一种将 Twitter Bootstrap 样式的导航与 Angular2 一起使用的方法,但无法将 active
class 应用于所选 [=20] 的父元素=].发现@alex-correia-santos 的解决方案非常有效!
包含您的选项卡的组件必须导入路由器并在其构造函数中定义它,然后您才能进行必要的调用。
这是我的实施的简化版本...
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 ){}
}
下面是使用 RouteData 根据当前路由设置菜单栏项目样式的方法:
RouteConfig 包含带有选项卡的数据(当前路线):
@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>
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;
}
}
how do you determine what the currently active route is?
更新:根据 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
}
在简单的情况下使用 routerLinkActive
很好,当有 link 并且您想应用一些 类 时。但在更复杂的情况下,您可能没有 routerLink 或者您需要更多东西,您可以创建并使用 pipe:
@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>
并且不要忘记在管道依赖项中包含管道 ;)
Router
in Angular 2 RC 不再定义 isRouteActive
和 generate
方法。
urlTree
- Returns the current url tree.
createUrlTree(commands: any[], segment?: RouteSegment)
- Applies an array of commands to the current url tree and creates a new url tree.
尝试关注
<li
[class.active]=
"router.urlTree.contains(router.createUrlTree(['/SignIn', this.routeSegment]))">
注意,routeSegment : RouteSegment
必须注入到组件的构造函数中。
Router class 的实例实际上是一个 Observable,它 returns 每次更改时都是当前路径。我就是这样做的:
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;
}
}
然后在我的 HTML 中:
<a [routerLink]="['Contact']" class="item" [class.active]="isCurrentRoute('contact')">Contact</a>
这是在 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>
使用新的 Angular router,您可以向所有链接添加 [routerLinkActive]="['your-class-name']"
属性:
<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>
或者简化的非数组格式,如果只需要一个 class:
<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>
如果只需要一个 class,或者更简单的格式:
<a [routerLink]="['/home']" routerLinkActive="is-active">Home</a>
有关详细信息,请参阅 poorly documented routerLinkActive
directive。 (我主要是通过反复试验来解决这个问题的。)
更新:现在可以找到 routerLinkActive
指令的更好文档 here。 (感谢@Victor Hugo Arango A. 在下面的评论中。)
另一种解决方法。在 Angular Router V3 Alpha 中更容易。通过注入 Router
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>
如果也应该标为use
routerLinkActive="some class list" [routerLinkActiveOptions]="{ exact: false }"
据我所知,exact: false
将成为 RC.4 中的默认值
在 Angular2 RC2 中你可以使用这个简单的实现
<a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
这会将 class active
添加到匹配 url 的元素中,阅读更多相关信息 here
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);
}
以下是迄今为止发布的 Angular 2 RC 版本的所有版本对此问题的回答:
RC4 和 RC3:
用于将 class 应用于 link 或 link 的祖先:
<li routerLinkActive="active"><a [routerLink]="['/home']">Home</a></li>
/home 应该是 URL 而不是路由名称,因为从路由器 v3 开始,名称 属性 不再存在于路由对象上。
在此 link.
了解有关 routerLinkActive 指令的更多信息
根据当前路线将class应用于任何div:
- 将 Router 注入到组件的构造函数中。
- 用户router.url进行比较。
例如
<nav [class.transparent]="router.url==('/home')">
</nav>
RC2 和 RC1:
使用 router.isRouteActive 和 class 的组合。*。例如,根据 Home Route 应用 active class。
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
如已接受答案的评论之一所述,routerLinkActive
指令也可以应用于实际 <a>
标记的容器。
因此,例如 with Twitter Bootstrap tabs 其中活动 class 应该应用于包含 link:
<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>
非常整洁!我想该指令检查标签的内容并使用 routerLink
指令查找 <a>
标签。
我正在使用 angular 路由器 ^3.4.7
,但 routerLinkActive
指令仍然存在问题。
如果您有多个 link 具有相同的 url,它就无法正常工作,而且它似乎不会一直刷新。
受@tomaszbak 回答的启发,我创建了一个little component 来完成这项工作
假设您想将 CSS 添加到我的活动 state/tab。使用 routerLinkActive 激活您的路由 link.
注意:'active' 是我的 class 名字
<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 版本 4+,您不需要使用任何复杂的解决方案。您可以简单地使用 [routerLinkActive]="'is-active'"
.
例如 bootstrap 4 导航 link:
<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>
只是想我会添加一个不使用任何打字稿的示例:
<input type="hidden" [routerLink]="'home'" routerLinkActive #home="routerLinkActive" />
<section *ngIf="home.isActive"></section>
routerLinkActive
变量绑定到模板变量,然后根据需要re-used。不幸的是,唯一的警告是你不能在 <section>
元素上拥有所有这些,因为 #home
需要解析 prior 到解析器点击 <section>
.
angular 5 个用户的简单解决方案是,只需将 routerLinkActive
添加到列表项。
routerLinkActive
指令通过 routerLink
指令与路由关联。
它将一个 classes 数组作为输入,如果它的路由当前处于活动状态,它将添加到它附加到的元素中,如下所示:
<li class="nav-item"
[routerLinkActive]="['active']">
<a class="nav-link"
[routerLink]="['home']">Home
</a>
</li>
如果我们当前正在查看主页路线,上面将向锚标记添加一个 class active。
纯html模板如
<a [routerLink]="['/home']" routerLinkActive="active">Home</a>
<a [routerLink]="['/about']" routerLinkActive="active">About us</a>
<a [routerLink]="['/contact']" routerLinkActive="active">Contacts</a>
首先在您的 .ts 中导入 RouterLinkActive
import { RouterLinkActive } from '@angular/router';
现在在您的 HTML
中使用 RouterLinkActive
<span class="" routerLink ="/some_path" routerLinkActive="class_Name">Value</span></a>
提供一些 css 到 class "class_Name" ,因为当这个 link 将是 active/clicked 你会在 span 上找到这个 class边检查边
从 Angular 8 开始,这个有效:
<li routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">
<a [routerLink]="['/']">Home</a>
</li>
{ exact: true }
确保它匹配 url.
而在最新版本 angular 中,您只需检查 router.isActive(routeNameAsString)
。例如,请参见下面的示例:
<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>
并确保您没有忘记在组件中注入路由器。
2020 年如果你想在没有 [routerLink] 的元素上设置活动 class - 你可以简单地做:
<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 并且它需要一个 child 元素。如果你想改变它,你需要去掉 superclass.nativeElement
.
上的 children
这对我 active/inactive 路线有帮助:
<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive" [ngClass]="rla.isActive ? 'classIfActive' : 'classIfNotActive'">
</a>
注意: 这里有许多不同的答案,而且大多数都曾经有效。事实上,随着 Angular 团队更改其路由器,有效的方法已经更改了很多次。最终将成为 中 Angular 路由器的 Router 3.0 版本打破了许多这些解决方案,但提供了一个非常简单的解决方案。从 RC.3 开始,首选解决方案是使用 [routerLinkActive]
,如
在 Angular 应用程序中(在我写这篇文章时,当前版本为 2.0.0-beta.0),您如何确定当前活动的路由是什么?
我正在开发一个使用 Bootstrap 4 的应用程序,我需要一种方法来将导航 links/buttons 标记为活动,当它们的关联组件显示在 <router-output>
标记中时.
我意识到当其中一个按钮被点击时我可以自己保持状态,但这不包括有多个路径进入同一路线的情况(比如主导航菜单和本地菜单)主组件中的菜单)。
如有任何建议或链接,我们将不胜感激。谢谢
您可以通过将 Location
对象注入控制器并检查 path()
来检查当前路由,如下所示:
class MyController {
constructor(private location:Location) {}
... location.path(); ...
}
您必须确保首先导入它:
import {Location} from "angular2/router";
然后您可以使用正则表达式匹配返回的路径以查看哪个路由处于活动状态。请注意,Location
class returns 是规范化路径,无论您使用的是哪个 LocationStrategy
。因此,即使您使用 HashLocationStragegy
,返回的路径仍将采用 /foo/bar
not #/foo/bar
我已经在另一个问题中回答了这个问题,但我相信它也可能与这个问题相关。这是原始答案的 link:
我一直在尝试设置 active class 而不必确切知道当前位置 (使用路线名称)。到目前为止,我得到的最佳解决方案是使用 Router
class.
router.isRouteActive(instruction): Boolean
接受一个参数,它是一个路由 Instruction
对象和 returns true
或 false
该指令是否适用于当前路线。您可以使用 Router
的 generate(linkParams: Array). LinkParams follows the exact same format as a value passed into a routerLink 指令(例如 router.isRouteActive(router.generate(['/User', { user: user.id }]))
)生成路由 Instruction
。
这就是 RouteConfig 的样子 (我稍微调整了一下以显示参数的用法):
@RouteConfig([
{ path: '/', component: HomePage, name: 'Home' },
{ path: '/signin', component: SignInPage, name: 'SignIn' },
{ path: '/profile/:username/feed', component: FeedPage, name: 'ProfileFeed' },
])
View 看起来像这样:
<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>
到目前为止,这是我首选的问题解决方案,可能对您也有帮助。
我解决了我在这个 router-link-active
。
@Component({
styles: [`.router-link-active { background-color: red; }`]
})
export class NavComponent {
}
基于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));
}
}
并像这样使用它:
<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>
我正在寻找一种将 Twitter Bootstrap 样式的导航与 Angular2 一起使用的方法,但无法将 active
class 应用于所选 [=20] 的父元素=].发现@alex-correia-santos 的解决方案非常有效!
包含您的选项卡的组件必须导入路由器并在其构造函数中定义它,然后您才能进行必要的调用。
这是我的实施的简化版本...
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 ){}
}
下面是使用 RouteData 根据当前路由设置菜单栏项目样式的方法:
RouteConfig 包含带有选项卡的数据(当前路线):
@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>
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;
}
}
how do you determine what the currently active route is?
更新:根据 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
}
在简单的情况下使用 routerLinkActive
很好,当有 link 并且您想应用一些 类 时。但在更复杂的情况下,您可能没有 routerLink 或者您需要更多东西,您可以创建并使用 pipe:
@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>
并且不要忘记在管道依赖项中包含管道 ;)
Router
in Angular 2 RC 不再定义 isRouteActive
和 generate
方法。
urlTree
- Returns the current url tree.
createUrlTree(commands: any[], segment?: RouteSegment)
- Applies an array of commands to the current url tree and creates a new url tree.
尝试关注
<li
[class.active]=
"router.urlTree.contains(router.createUrlTree(['/SignIn', this.routeSegment]))">
注意,routeSegment : RouteSegment
必须注入到组件的构造函数中。
Router class 的实例实际上是一个 Observable,它 returns 每次更改时都是当前路径。我就是这样做的:
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;
}
}
然后在我的 HTML 中:
<a [routerLink]="['Contact']" class="item" [class.active]="isCurrentRoute('contact')">Contact</a>
这是在 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>
使用新的 Angular router,您可以向所有链接添加 [routerLinkActive]="['your-class-name']"
属性:
<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>
或者简化的非数组格式,如果只需要一个 class:
<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>
如果只需要一个 class,或者更简单的格式:
<a [routerLink]="['/home']" routerLinkActive="is-active">Home</a>
有关详细信息,请参阅 poorly documented routerLinkActive
directive。 (我主要是通过反复试验来解决这个问题的。)
更新:现在可以找到 routerLinkActive
指令的更好文档 here。 (感谢@Victor Hugo Arango A. 在下面的评论中。)
另一种解决方法。在 Angular Router V3 Alpha 中更容易。通过注入 Router
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 中的默认值
在 Angular2 RC2 中你可以使用这个简单的实现
<a [routerLink]="['/dashboard']" routerLinkActive="active">Dashboard</a>
这会将 class active
添加到匹配 url 的元素中,阅读更多相关信息 here
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);
}
以下是迄今为止发布的 Angular 2 RC 版本的所有版本对此问题的回答:
RC4 和 RC3:
用于将 class 应用于 link 或 link 的祖先:
<li routerLinkActive="active"><a [routerLink]="['/home']">Home</a></li>
/home 应该是 URL 而不是路由名称,因为从路由器 v3 开始,名称 属性 不再存在于路由对象上。
在此 link.
了解有关 routerLinkActive 指令的更多信息根据当前路线将class应用于任何div:
- 将 Router 注入到组件的构造函数中。
- 用户router.url进行比较。
例如
<nav [class.transparent]="router.url==('/home')">
</nav>
RC2 和 RC1:
使用 router.isRouteActive 和 class 的组合。*。例如,根据 Home Route 应用 active class。
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
如已接受答案的评论之一所述,routerLinkActive
指令也可以应用于实际 <a>
标记的容器。
因此,例如 with Twitter Bootstrap tabs 其中活动 class 应该应用于包含 link:
<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>
非常整洁!我想该指令检查标签的内容并使用 routerLink
指令查找 <a>
标签。
我正在使用 angular 路由器 ^3.4.7
,但 routerLinkActive
指令仍然存在问题。
如果您有多个 link 具有相同的 url,它就无法正常工作,而且它似乎不会一直刷新。
受@tomaszbak 回答的启发,我创建了一个little component 来完成这项工作
假设您想将 CSS 添加到我的活动 state/tab。使用 routerLinkActive 激活您的路由 link.
注意:'active' 是我的 class 名字
<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 版本 4+,您不需要使用任何复杂的解决方案。您可以简单地使用 [routerLinkActive]="'is-active'"
.
例如 bootstrap 4 导航 link:
<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>
只是想我会添加一个不使用任何打字稿的示例:
<input type="hidden" [routerLink]="'home'" routerLinkActive #home="routerLinkActive" />
<section *ngIf="home.isActive"></section>
routerLinkActive
变量绑定到模板变量,然后根据需要re-used。不幸的是,唯一的警告是你不能在 <section>
元素上拥有所有这些,因为 #home
需要解析 prior 到解析器点击 <section>
.
angular 5 个用户的简单解决方案是,只需将 routerLinkActive
添加到列表项。
routerLinkActive
指令通过 routerLink
指令与路由关联。
它将一个 classes 数组作为输入,如果它的路由当前处于活动状态,它将添加到它附加到的元素中,如下所示:
<li class="nav-item"
[routerLinkActive]="['active']">
<a class="nav-link"
[routerLink]="['home']">Home
</a>
</li>
如果我们当前正在查看主页路线,上面将向锚标记添加一个 class active。
纯html模板如
<a [routerLink]="['/home']" routerLinkActive="active">Home</a>
<a [routerLink]="['/about']" routerLinkActive="active">About us</a>
<a [routerLink]="['/contact']" routerLinkActive="active">Contacts</a>
首先在您的 .ts 中导入 RouterLinkActive
import { RouterLinkActive } from '@angular/router';
现在在您的 HTML
中使用 RouterLinkActive<span class="" routerLink ="/some_path" routerLinkActive="class_Name">Value</span></a>
提供一些 css 到 class "class_Name" ,因为当这个 link 将是 active/clicked 你会在 span 上找到这个 class边检查边
从 Angular 8 开始,这个有效:
<li routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">
<a [routerLink]="['/']">Home</a>
</li>
{ exact: true }
确保它匹配 url.
而在最新版本 angular 中,您只需检查 router.isActive(routeNameAsString)
。例如,请参见下面的示例:
<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>
并确保您没有忘记在组件中注入路由器。
2020 年如果你想在没有 [routerLink] 的元素上设置活动 class - 你可以简单地做:
<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 并且它需要一个 child 元素。如果你想改变它,你需要去掉 superclass.nativeElement
.
这对我 active/inactive 路线有帮助:
<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive" [ngClass]="rla.isActive ? 'classIfActive' : 'classIfNotActive'">
</a>