4

In my application there are two routes, home and page1

the are two anchor tags which navigate to relevant routes, I change the background color of the active tab to red, the default color is yellow.

  1. when active route is '/' the home tab become red - OK
  2. when I click on '/page1' the home tab and page 1 both becomes red, Why? I aspect only the page 1 tab become red.

here are the code snippets

const routes: Routes = [
  { path: 'page1', component: Page1Component },
  { path: '', component: HomeComponent },
  { path: '**', redirectTo: '' }
];
<a routerLink="/" [routerLinkActive]="['active-tab']">Home</a>

<a routerLink="/page1" [routerLinkActive]="['active-tab']">Page 1</a>

<router-outlet></router-outlet>
a{
  padding: 10px;
  background: yellow;
}

a.active-tab{
  background: red;
}

Here is the stackblitz code of the issue you can see when click on /page2 route both the tabs becomes active.

I tried the solution

<a routerLink="/" [routerLinkActive]="['active-tab']" [routerLinkActiveOptions]="{exact: true}"> Home </a>

but when I access the home route with query parameters(http://localhost:4200/?myParam=5), the home tab NOT being activated.

Azad
  • 5,144
  • 4
  • 28
  • 56

2 Answers2

4

This is a long running issue

As you have found, you can either

  1. Match the exact url, including query params

OR

  1. Match the current route, including descendant routes

The general workaround for this is to avoid using routerLinkActive where necessary, and instead check the route manually.

component.html

<a routerLink="/" [class.active-tab]="isLinkActive('/')">
  Home
</a>

component.ts

constructor(private router: Router) {}

isLinkActive(url): boolean {
  const queryParamsIndex = this.router.url.indexOf('?');
  const baseUrl = queryParamsIndex === -1 ? this.router.url : this.router.url.slice(0, queryParamsIndex);
  return baseUrl === url;
}

You should still use routerLinkActive where you can though, and keep an eye on this issue for the future for if/when the Angular team manage to build the functionality that a lot of people are asking for.

DEMO: https://stackblitz.com/edit/angular-cac4a3

Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40
1

This is the issue actually. The url doesn't stay the same (or in other words exact if some params are there). BUt someone has a way around this already, in fact 2. Sharing the link of the stackoverflow post for similar issue. The main answer is your go to solution and the next post after the accepted answer one (if you have only 2 tabs use that) its with hidden attribute (cameroon's answer).

Visit the following link for details:

How to use "routerLinkActive" with query params in Angular 6?

Wahab Shah
  • 2,066
  • 1
  • 14
  • 19