Apply CSS to active router link [Angular 2]

后端 未结 3 1705
面向向阳花
面向向阳花 2021-01-18 10:34

I would like to apply special CSS style properties to active router links:

相关标签:
3条回答
  • 2021-01-18 11:13

    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.

    0 讨论(0)
  • 2021-01-18 11:21

    Currently Angular 2 has a built in attribute that you can use on any link that is used with [routerLink] it is routerLinkActive so all you need to do is have:

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

    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

    0 讨论(0)
  • 2021-01-18 11:29

    The new router has a directive called "routerLinkActive" which is what your interested in.

    Ex.<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."

    0 讨论(0)
提交回复
热议问题