58

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

1
  • Same issue here Commented Oct 7, 2016 at 11:07

4 Answers 4

104

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>
Sign up to request clarification or add additional context in comments.

1 Comment

If I go to about page from home page and refresh the page, I still see home page active. Any idea how to fixed this ?
47

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

Comments

2

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.