简体   繁体   中英

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM