Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 628
Platus Avatar asked Jul 15 '16 18:07

Platus


People also ask

What is the use of routerLinkActive in angular?

RouterLinkActivelinkTracks whether the linked route of an element is currently active, and allows you to specify one or more CSS classes to add to the element when the linked route is active.

How do I know if my routerLink is active?

routerLinkActive is simply an indicator of whether this link represents the active route. @jessepinho - Tried it - [routerLinkActive]="'active'" will only work if you also have [routerLink] in the a-tag. If you had (click)="navitageTo('/route')" instead of [routerLink], and in that function, you called this.

What is the difference between routerLink and routerLink in angular?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.


1 Answers

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

like image 173
Jarod Moser Avatar answered Sep 19 '22 17:09

Jarod Moser