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

Twitter BootstrapAngularNavAngular2 Routing

Twitter Bootstrap Problem Overview


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

Twitter Bootstrap Solutions


Solution 1 - Twitter Bootstrap

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"

Solution 2 - Twitter Bootstrap

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>

Solution 3 - Twitter Bootstrap

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.

Solution 4 - Twitter Bootstrap

Use the isRouteActive with generate from the Router class.

According to docs:

> generate(linkParams: any[]) : Instruction > > Generate an Instruction based on the provided Route Link DSL.

and

> isRouteActive(instruction: Instruction) : boolean > > Given an instruction, returns true if the instruction is currently > active, otherwise false.

<li [class.active]="router.isRouteActive(router.generate(['/Home']))">
   <a [routerLink]="['/Home']">Home</a>
</li>

Solution 5 - Twitter Bootstrap

This does the trick (using RC5)

<li [class.active]="homeLink.classList.contains('active')">
    <a #homeLink routerLink="/home" routerLinkActive="active">Home</a>
</li>

Solution 6 - Twitter Bootstrap

On RC2 that did not work for me. I ended up using

   <li  (click)="setActive('home')" class="{{getActive('home')}}"> <a [routerLink]="['/FullScreen']">Home</a></li>

and in the code behind tracked it

    currentChoice: string = "home";

   setActive(choice: string): void{
       this.currentChoice = choice;
   }

   getActive(choice: string) : string{
       if(this.currentChoice == choice)
            return "active";
       else
            return "not";

   }

Solution 7 - Twitter Bootstrap

In "@angular/router": "^3.3.1", the difference in the previous version is the bracket in the routerLinkActive

[routerLinkActive]="['active']"

In final release, ng2 will complain so just remove the bracket

routerLinkActive="active"

Solution 8 - Twitter Bootstrap

In the case of multiple links try this

<ul class="navbar-nav ml-auto"> 
<li class="nav-item " routerLink="" routerLinkActive="active" [routerLinkActiveOptions]="{exact:true}">
<a class="nav-link" routerLink="">Home </a></li>
<li class="nav-item" [routerLinkActive]="['active']">
<a class="nav-link" routerLink="/aboutus">About</a></li>
<li class="nav-item" [routerLinkActive]="['active']">
<a class="nav-link" routerLink="/gallery">Gallery</a>
 </li>
<li class="nav-item" [routerLinkActive]="['active']">
<a class="nav-link" routerLink="/contactus">Contact Us</a>
</li>
</ul>

Solution 9 - Twitter Bootstrap

The version "@angular/router": "^3.3.1"

I simply put the name of the route, that I declare in my app.route.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule }   from '@angular/router';

import { HomeComponent } from './home/home.component';
import { DeclarationsComponent } from './declarations/declarations.component';

const appRoutes: Routes = [
    { path: '', pathMatch: 'full', component: HomeComponent },
    { path: 'declarations', pathMatch: 'full', component: DeclarationsComponent }
];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

And in the view, I just write the name of the route

  <ul class="nav navbar-nav">
     <li routerLinkActive="active"><a routerLink="">Home</a></li>
     <li><a routerLink="declarations">SAV</a></li>
  </ul>

Solution 10 - Twitter Bootstrap

<a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact:
true}">Bob</a>

Solution 11 - Twitter Bootstrap

import { Directive, HostListener, ElementRef, HostBinding, Renderer2 } from '@angular/core';

@Directive({
  selector: '[appNavDropdown]'
})
export class NavDropdownDirective {
  isOpen:boolean =false;
  counter:number = 0;
  constructor(private el: ElementRef, private render: Renderer2) { }

  @HostBinding('class.open') get opened() {
    return this.isOpen;
  }

  @HostListener('click') onmouseClick()
  {
    this.counter++
    console.log();
    if(this.counter % 2 == 1)//odd
    {
      let part = this.render.parentNode(this.el.nativeElement);
      this.render.addClass(part,'open');
      this.isOpen = true;
    }else{
      let part = this.render.parentNode(this.el.nativeElement);
      this.render.removeClass(part,'open');
      this.isOpen = false;
    }
  }
  // @HostListener('mouseleave') onmouseLeave()
  // {
  //   let part = this.render.parentNode(this.el.nativeElement);
  //   this.render.removeClass(part,'open');
  //   this.isOpen = false;
  // }

  toggleClose() {
    // let part = this.render.parentNode(this.el.nativeElement)
    //this.menuclick = false;

  }
  toggle() {
    this.el.nativeElement.classList.toggle('open');
  }
}

/**
* Allows the dropdown to be toggled via click.
*/
@Directive({
  selector: '[appNavDropdownToggle]'
})
export class NavDropdownToggleDirective {
  constructor(private dropdown: NavDropdownDirective) { }

  @HostListener('click', ['$event'])
  toggleOpen($event: any) {
    console.log($event)
    $event.preventDefault();
  //  this.dropdown.toggleClose()
   this.dropdown.toggle();
  }
}

export const NAV_DROPDOWN_DIRECTIVES = [NavDropdownDirective, NavDropdownToggleDirective];

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHongbo MiaoView Question on Stackoverflow
Solution 1 - Twitter BootstrapBert DeterdView Answer on Stackoverflow
Solution 2 - Twitter BootstrapAndrew RothView Answer on Stackoverflow
Solution 3 - Twitter BootstrapJohannesView Answer on Stackoverflow
Solution 4 - Twitter BootstrappixelbitsView Answer on Stackoverflow
Solution 5 - Twitter BootstraprcomblenView Answer on Stackoverflow
Solution 6 - Twitter BootstrapMatrimView Answer on Stackoverflow
Solution 7 - Twitter BootstrapbrijmcqView Answer on Stackoverflow
Solution 8 - Twitter BootstrapSachinView Answer on Stackoverflow
Solution 9 - Twitter BootstrapShigiang LiuView Answer on Stackoverflow
Solution 10 - Twitter BootstrapYathishView Answer on Stackoverflow
Solution 11 - Twitter BootstrapFerozView Answer on Stackoverflow