How to set Bootstrap navbar "active" class in Angular 2?
How can I set Bootstrap navbar "active" class in Angular 2? I only found Angular 1 way.
When I go to About page, add class="active"
to About, and remove class="active"
on Home.
<ul class="nav navbar-nav">
<li class="active"><a [routerLink]="['Home']">Home</a></li>
<li><a [routerLink]="['About']">About</a></li></li>
</ul>
Thanks
If you use the new 3.0.0. component router ( https://github.com/angular/vladivostok ) you can use the routerLinkActive directive. No further javascript required.
<ul class="nav navbar-nav">
<li [routerLinkActive]="['active']"> <a [routerLink]="['one']">One</a></li>
<li [routerLinkActive]="['active']"> <a [routerLink]="['second']">Second</a></li>
</ul>
I used "@angular/router": "^3.0.0-alpha.7"
Bert Deterd's answer is correct, but there's one thing that can be added.
If one route is a substring of another route, you will see something like this happen: 2 active anchors
You can add this to make it match exact routes only:
[routerLinkActiveOptions]="{exact:true}"
Full Example:
<ul class="nav navbar-nav">
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/']">Home</a>
</li>
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/about']">About</a>
</li>
<li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
<a [routerLink]="['/calendar']">Calendar</a>
</li>
</ul>
For the latest version of Angular2 RC4 the following simple code works:
<li [class.active]="router.url==='/about'"><a [routerLink]="['/about']">About</a></li>
Using import {Router} from "@angular/router"; and put the router in the constructor.