How to set Bootstrap navbar "active" class in Angular 2? How to set Bootstrap navbar "active" class in Angular 2? angular angular

How to set Bootstrap navbar "active" class in Angular 2?


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.