Edwin Sulaiman
Edwin Sulaiman

Reputation: 739

Angular 9 routerLinkActive not working properly

My problem is when I click other router link, the class of router link

<div class="side-link" [routerLink]="['/']" [routerLinkActive] = "['link-active']">Dashboard</div>

is still active, so I have 2 active class links.

app-routing.module.ts

  {
    path: '',
    component: SidebarComponent, 
    children: [
      {path: '', component: DashboardComponent },
      {path: 'user-list', component: DashboardComponent },
      {path: 'account', component: DashboardComponent },
      {path: 'setting', component: DashboardComponent }
    ]
  }

app.component.html

    <div class="side-link" [routerLink]="['/']" [routerLinkActive] = "['link-active']">Dashboard</div>
    <div class="side-link" [routerLink]="['/user-list']" [routerLinkActive] = "['link-active']">User List</div>
    <div class="side-link" [routerLink]="['/account']" [routerLinkActive] = "['link-active']">Account</div>
    <div class="side-link" [routerLink]="['/setting']" [routerLinkActive] = "['link-active']">Setting</div>

Upvotes: 7

Views: 8554

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

If you're matching against a route whose URL is a partial match against other routes, you need to state that you want to perform an exact match.

Unless you have one route, the relative URL / is always going to be treated as a partial match against other routes.

You can use routerLinkActiveOptions to state that you want to perform an exact match.

<div class="side-link" routerLink="/" routerLinkActive="link-active"
    [routerLinkActiveOptions]="{ exact: true }" >
  Dashboard
</div>

By partial match, I mean that a URL is also the prefix for another route.

For example: /child is a partial match of /child/grand-child.

This is not affected by whether routes are declared as children or not.

Upvotes: 10

Related Questions