在Angular 2中获得活动链接 [英] Get active link in Angular 2
问题描述
我试图在Angular 2中获得活动链接,以便可以在模板中更新CSS.
I am attempting to get the active link in Angular 2 so I can update my css in my template.
这是我在Google的帮助下所做的事情:
This is what I have done with the help of google:
export class AppComponent {
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;
}
}
我的模板如下:
<li class="some-class" [ngClass]="{active: isActive('some-route')}">
<a [routerLink]="['SomeRoute']" class="menu-item" ><span>Link1</span></a>
</li>
虽然可行,但我注意到 RouterLink指令具有方法:isRouteActive.
While this works, I note the RouterLink directive has the method: isRouteActive.
这似乎是使用此操作链接类的明智方法.
This would seem like a sensible way to manipulate the link class using this.
但是我如何使用它?
推荐答案
更新RC.3:
在RC.3中,有一个新指令 routerLinkActive
已添加.
In RC.3 there was a new directive routerLinkActive
added.
routerLinkActive="classA classB class" [routerLinkActiveOptions]="{exact: true}"
原始:
角度路由器会在活动路由器链接上自动设置router-link-active
类.
Angular router sets router-link-active
class automatically on active router links.
如果您想要自定义类,可以使用类似的
If you want custom classes you can use something like
- Changing the default name of "router-link-active" class by writing a custom directive that adds new class
- In Angular 2 how do I assign a custom class to an active router link?
另请参见
https://github.com/angular/angular/issues/5334
这篇关于在Angular 2中获得活动链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!