0

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>
6
  • 2
    That's what routerLinkActive does all by itself. Remove the [ngClass] and the (click) handler: they're useless. Commented Aug 16, 2018 at 6:19
  • I removed it ,still not working Commented Aug 16, 2018 at 6:21
  • 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. Commented Aug 16, 2018 at 6:22
  • not-working : Working after clicking 2 times on link. Commented Aug 16, 2018 at 6:27
  • 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 Commented Aug 16, 2018 at 6:29

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Can I use router-outlet 2 times in same project?
Do we need to create different routing module fot that
@kedarkulk no you don't however you need to define child routes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.