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.
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.
This is a long running issue
As you have found, you can either
OR
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.