Kikus Kikus - 4 months ago 79
CSS Question

Apply CSS to active router link [Angular 2]

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



<a [routerLink]='link'>{{name}}</a>





Here is what I tried so far (Using the default router-link-active class):



.router-link-active {
color: #000;
font-weight: bold;
}





It doesn't work and I really don't understand why.

Answer

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