Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Routing routerLinkActive class not getting removed from base page even on other link routing

I am providing a simple routing example which works well. The only issue is that routerLinkActive is adding class 'baboossa' to whichever link is active. When I go from home to other links as 'about' or 'window' the link gets orange (due to baboossa class), but I can still see home also to be orange. Why now I am having 2 links with added classes from routerLinkActive and class is not getting removed from home?

app.component.html

<ul>
  <li><a [routerLink]="''" routerLinkActive="baboossa">Home</a></li>
  <li><a [routerLink]="'/about'" routerLinkActive="baboossa">About</a></li>
  <li><a [routerLink]="'/window'" routerLinkActive="baboossa">Window</a></li>
</ul>

<router-outlet></router-outlet>

app.module.ts

import { RouterModule } from '@angular/router';

imports: [
  RouterModule.forRoot([
    {path:'', component: HomeComponent},
    {path:'about', component: AboutComponent},
    {path:'window', component:WindowComponent}
  ])
]

styles.css

.baboossa {background:orange;}

Results:

enter image description here enter image description here enter image description here

Can someone point out the problem why I am getting 2 orange backgrounds on other active links than baseone (home)?

enter image description here

like image 802
Deadpool Avatar asked Sep 10 '25 13:09

Deadpool


1 Answers

You can archive with two methods:

  1. Add routerLinkActiveOptions [routerLinkActiveOptions]="{ exact: true }" with routerLinkActive.

Like this : [routerLink]="''" [routerLinkActive]="['baboossa']" [routerLinkActiveOptions]="{ exact: true }".

  1. Redirect your empty router path : '' to any particular path like '{ path : '', redirectTo: 'home'} in your router module.

Like this :

[{
    path: '',    
    pathMatch : 'full',
    redirectTo: 'home'
},
{
    path: 'home',    
    component: HomeComponent
}]

and change [routerLink]="''" with [routerLink]="'home'".

Here is the Stackblitz

like image 91
Shashikant Devani Avatar answered Sep 13 '25 02:09

Shashikant Devani