Search code examples
angularangular8angular-router

Why home tab is always active?


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.


Solution

  • 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