How to set Bootstrap navbar “active” class in Angular 2?

后端 未结 11 670
被撕碎了的回忆
被撕碎了的回忆 2020-12-07 18:36

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

相关标签:
11条回答
  • 2020-12-07 19:01

    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>
    
    0 讨论(0)
  • 2020-12-07 19:01

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

    0 讨论(0)
  • 2020-12-07 19:03

    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.

    0 讨论(0)
  • 2020-12-07 19:08

    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"

    0 讨论(0)
  • 2020-12-07 19:09

    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"
    
    0 讨论(0)
提交回复
热议问题