Seting Bootstrap navbar “active” class in Angular 2/4/5

Specify the active class in routerLinkActive directive of anchor tag like below.

<ul class="nav navbar-nav">
  <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
    <a [routerLink]="['/']">Home</a>
  <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
    <a [routerLink]="['/about']">About</a>
  <li [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
    <a [routerLink]="['/contact']">Contact Us</a>

PS: By making { exact: true } in routerLinkActiveOptions will activate the route only when the whole path matches.

routerLink is not working in Angular 5

If the routerLink is not working in your Angular 2/4/5 application, here are some common mistakes and solutions.

  • Check if you have added RouterModule in the imports of Module where you created this component.

For example, if you have created a NavComponent in NavigationModule and imported in your HomeModule and using it. Then you have to import ReportModule in your NavigationModule.

Like –

import { RouterModule } from '@angular/router';
  imports: [
declarations: [NavComponent],
exports: [NavComponent]
export class NavigationModule { }
  • If you have any computations in the routerLink, like appending a value dynamically, enclose routerLink with square brackets
<a [routerLink]="['/car/', carModelName].concat(details)"></a>

Here, carModelName and details can be class variables.
Hope this helps!