0
votes

I am trying to add active class to routerLink in Angular 6.My sidnav component consist of all routerLinks. After clicking on routerlink that particular link should be active and the particular component should appear.I tried using focus css,it is working when I click on Link 2 times.May be I am getting error because I am use sidenav selector in bill-to component.

sidenav component html Code:

 <li ><a  [ngClass]="{'red-input':clicked}" routerLink="/bill-to" routerLinkActive="red-input" (click)="Clicked()" >Bill To</a></li>
<li ><a   [ngClass]="{'red-input':clicked}" routerLink="/ship-to" routerLinkActive="red-input"  (click)="Clicked()"> Ship To</a></li>

ts code:

 clicked: boolean = false;

 Clicked() {
this.clicked = true;
 }

Bill-to component code:

   <div class="container-fluid">
<div class="row">
  <div class="col-sm-3">
     <app-sidenav></app-sidenav>       
  </div>

  <div class="col-sm-8" style="margin-top:1%;">

  </div>
  </div>
  </div>
1
That's what routerLinkActive does all by itself. Remove the [ngClass] and the (click) handler: they're useless. - JB Nizet
I removed it ,still not working - kedar kulkarni
Define "not working", precisely. If you get an error, post it, of course. Why do you have a sidenav inside the bill-to component? It makes no sense. The sidenav allows displaying it, so it's already displayed outseid of this component. - JB Nizet
not-working : Working after clicking 2 times on link. - kedar kulkarni
not-working : Working after clicking 2 times on link.I am using sidenav inside bill-to component because ,I am using sidenav(parent compnent) second time in this project.This sidenav is not considered inside routeroutlet thus I used sidenav inside bill-to component - kedar kulkarni

1 Answers

2
votes

You should use [routerLinkActive]="'your-class-name'". It will detect if route is active and apply class by itself.

DEMO https://stackblitz.com/edit/angular-gyhshq