Search code examples
angularangular-routingangular-router

Angular Routing routerLinkActive


For some reason when i go to heroes/2 link both of links get .active class from routerLinkActive, but i expect only c2.component should get it. What is my mistake?

P.S. If i go heroes link = only this link get active.

    const appRoutes: Routes = [
            { path: 'heros', component: c1},
            { path: 'heros/:id', component: c2},
        ];

  <a routerLink="/heros" routerLinkActive="active">heros</a>
  <a routerLink="/heros/2" routerLinkActive="active">hero 2</a>

Solution

  • You can configure RouterLinkActive by passing exact: true. This will add the classes only when the url matches the link exactly.

    <a routerLink="/heros" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}">heros</a>
    <a routerLink="/heros/2" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}">hero 2</a>