0

I have 3 list items and I want to add active class based on the URL. Here are my list items:

  <ul class="nav nav-tabs my-4">
    <li class="nav-item">
      <a routerLink='/' class="nav-link" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Home</a>
    </li>
    <li class="nav-item">
      <a routerLink='products' class="nav-link" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Products</a>
    </li>
    <li class="nav-item">
      <a routerLink='users' class="nav-link" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">Users</a>
    </li>
  </ul>

What I want to do is, I want to activate products list item even though the URL is like this: http://localhost:4200/products/1 or like this: http://localhost:4200/products?page=2&order=newest

What can I do?

3
  • Did you try [routerLinkActiveOptions]="{exact: false}"? Commented Sep 4, 2020 at 7:32
  • I changed products's exact false and it worked. Could you explain what does exact do? Commented Sep 4, 2020 at 7:37
  • exact: true matches only if the entire path is the exact match of the route, which you actually didn't want. exact: false does the opposite of it, i.e. matches partial routes. Commented Sep 4, 2020 at 7:38

1 Answer 1

0

You don't need to write [routerLinkActiveOptions]="{exact: true}" for every link, as it matches your link exactly and won't add active class if route is different even a param.

We add [routerLinkActiveOptions]="{exact: true}" normally for root('/') route as it is common route for other links as well.

Sign up to request clarification or add additional context in comments.

Comments