How to set Bootstrap navbar “active” class in Angu

2019-01-16 12:17发布

问题:

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

回答1:

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"



回答2:

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>


回答3:

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.



回答4:

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>


回答5:

This does the trick (using RC5)

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


回答6:

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";

   }


回答7:

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"


回答8:

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>


回答9:

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



回答10:

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];