gempir
gempir

Reputation: 1901

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 }"

Upvotes: 58

Views: 23391

Answers (4)

Ala Abid
Ala Abid

Reputation: 2326

As mentioned, use [routerLinkActiveOptions]="{ exact: true }"

If inside a for loop, you can do this

@for (route of navRoutes; track route.path) {
        <a mat-list-item
           [routerLink]="route.path"
           routerLinkActive
           [routerLinkActiveOptions]="{ exact: route.path === '/' }">
          <!--for styling, only if using Angular Material -->
          <!--#rla="routerLinkActive" [activated]="rla.isActive">-->
          {{ route.label }}
        </a>
}

Upvotes: 0

Mohamed Eldefrawy
Mohamed Eldefrawy

Reputation: 74

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 }".

Upvotes: 2

Peter Lorei
Peter Lorei

Reputation: 634

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

Upvotes: 47

Andrea
Andrea

Reputation: 16560

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>

Upvotes: 104

Related Questions