Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 routerLinkActive always active for base path

I have this code for my navbar:

<nav>   <a [routerLink]="['/']" [routerLinkActive]="['nav-active']">HOME</a>   <a [routerLink]="['/about']" [routerLinkActive]="['nav-active']">ABOUT</a>   <a [routerLink]="['/records']" [routerLinkActive]="['nav-active']">RECORDS</a> </nav> 

The problem is the HOME nav point always gets the class because / seems to be always active. Is this avoidable with a small and simple solution?

Thanks for the help

Edit:

this is the solution for now:

[routerLinkActiveOptions]="{ exact: true }"

like image 936
gempir Avatar asked Aug 02 '16 18:08

gempir


People also ask

What is routerLinkActive active?

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.

How do I set my router to active links?

Create the header component that contains the navigation links. Then apply the “routerLinkActive” on each router link and provide the CSS class to this property. Here we have created the “active” class in CSS file. Provide the { exact : true } to the root route to avoid multiple active router links.

Can I use RouterLink on Div?

Yes it can be attached to div tag, your route is probably wrong try add / in front of route.


Video Answer


1 Answers

As suggested by @TomRaine in this answer, you can add the property [routerLinkActiveOptions]="{ exact: true }" to your element:

<nav>   <a [routerLink]="['/']"        [routerLinkActive]="['nav-active']"       [routerLinkActiveOptions]="{ exact: true }">     HOME   </a>   ... </nav> 
like image 192
Andrea Avatar answered Oct 14 '22 05:10

Andrea