简体   繁体   中英

Angular 2 routerLinkActive always active for base path

I have this code for my navbar:

<nav>
  <a [routerLink]="['/']" [routerLinkActive]="['nav-active']">HOME</a>
  <a [routerLink]="['/about']" [routerLinkActive]="['nav-active']">ABOUT</a>
  <a [routerLink]="['/records']" [routerLinkActive]="['nav-active']">RECORDS</a>
</nav>

The problem is the HOME nav point always gets the class because / seems to be always active. Is this avoidable with a small and simple solution?

Thanks for the help

Edit:

this is the solution for now:

[routerLinkActiveOptions]="{ exact: true }"

As suggested by @TomRaine in this answer , you can add the property [routerLinkActiveOptions]="{ exact: true }" to your element:

<nav>
  <a [routerLink]="['/']" 
      [routerLinkActive]="['nav-active']"
      [routerLinkActiveOptions]="{ exact: true }">
    HOME
  </a>
  ...
</nav>

This appears to be a known issue. A few workarounds are detailed in this thread: https://github.com/angular/angular/issues/8397

From Github Thread:

"you need to add an additional option to your routerLink."

[routerLinkActiveOptions]="{ exact: true }"

Then your home route will only be active if you're on the exact route. The home route with an empty path will be a partial match on all routes

You can do something like this:

<button routerLink="/" [routerLinkActiveOptions]="{ exact: true }" routerLinkActive="nav-button-active"
                mat-button mat-raised-button
                class="w-100 mb-3 nav-buttons">
          Dashboard
</button>

Just make rure to add the property, [routerLinkActiveOptions]="{ exact: true }" .

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