Javascript 将 CSS 应用于活动路由器链接 [Angular 2]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38402498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apply CSS to active router link [Angular 2]
提问by Platus
I would like to apply special CSS style properties to active router links:
我想将特殊的 CSS 样式属性应用于活动路由器链接:
<a [routerLink]='link'>{{name}}</a>
Here is what I tried so far (Using the default router-link-active class):
这是我到目前为止所尝试的(使用默认的 router-link-active 类):
.router-link-active {
color: #000;
font-weight: bold;
}
It doesn't work and I really don't understand why.
它不起作用,我真的不明白为什么。
回答by Jarod Moser
Currently Angular 2 has a built in attributethat you can use on any link that is used with [routerLink]
it is routerLinkActive
so all you need to do is have:
目前 Angular 2 有一个内置属性,你可以在任何与[routerLink]
它一起使用的链接上使用它,routerLinkActive
所以你需要做的就是:
<a [routerLink]='link' routerLinkActive="router-link-active">{{name}}</a>
and then it will recognize which route is the current active route and apply your router-link-active class.
然后它将识别哪个路由是当前活动路由并应用您的 router-link-active 类。
NOTE:
笔记:
For those who are using routerLink on tags other than a
tags, (personally i am using it on a button) routerLinkActive
doesn't work but should work on the next release of the router - https://github.com/angular/angular/issues/9755
对于那些在标签以外的a
标签上使用 routerLink 的人,(我个人在按钮上使用它)routerLinkActive
不起作用,但应该适用于路由器的下一个版本 - https://github.com/angular/angular/issues /9755
回答by Ron
The new router has a directive called "routerLinkActive" which is what your interested in.
新路由器有一个名为“ routerLinkActive”的指令,这是您感兴趣的。
Ex.<a [routerLink]="/user/bob" routerLinkActive="active-link">Bob</a>
前任。<a [routerLink]="/user/bob" routerLinkActive="active-link">Bob</a>
"When the url is either '/user' or '/user/bob', the active-link class will be added to the a tag. If the url changes, the class will be removed."
“当 url 是 '/user' 或 '/user/bob' 时,active-link 类将被添加到 a 标签中。如果 url 更改,该类将被删除。”
回答by jake
Without knowing anything more, this is the direction I would point you in.
在不知道更多的情况下,这就是我要指出的方向。
<a [routerLink]='link' [ngClass]="{'router-link-active': routerLink.something === something}">{{name}}</a>
If routerLink.something === something
, or whatever expression you want, evaluates to true, the class (and styling) will be applied.
如果routerLink.something === something
或您想要的任何表达式的计算结果为 true,则将应用该类(和样式)。