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

Viewed 11102

I have a problem in Angular: I have three links, one of them has query params (due to using a resolver). If I click the first and the third link, the routerLinkActive is set. If I click the second link routerLinkActive is set too. But if I change the query parameter inside the component routerLinkActive gets unset.

So, I need to ignore the query params. But how does it work? Can anyone help me?

Here is my simple code:

<div class="col-12">
    <ul class="nav nav-pills nav-justified">
        <li class="nav-item">
            <a 
              class="nav-link" 
              routerLink="/einstellungen/allgemein"                             
              routerLinkActive="active">
              Allgemein
            </a>
        </li>
        <li class="nav-item">
            <a 
              class="nav-link" 
              [routerLink]="['/einstellungen/kalender']" 
              [queryParams]="{branch: myBranches[0].id}" 
              routerLinkActive="active"
              [routerLinkActiveOptions]="{exact: false}">
              Kalender verwalten
           </a>
        </li>
        <li class="nav-item">
            <a 
              class="nav-link" 
              *ngIf="user.is_admin" 
              routerLink="/einstellungen/filialen" 
              routerLinkActive="active">
              Filialen verwalten
            </a>
        </li>
    </ul>
</div>
3 Answers

RouteLinkActive will work only with exact query params. You may try passing {exact: false} as routerLinkActiveOptions. If that doesn't work

You can call a function inside [class.active] attributes.

<a class="nav-link" [routerLink]="['/einstellungen/kalender']" [queryParams]="{branch: myBranches[0].id}" [class.active]="isLinkActive('/my-link')">Kalender verwalten</a>

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

Using a hidden anchor tag and an html template variable:

<a [routerLink]="/einstellungen/kalender" routerLinkActive="" #rla="routerLinkActive" hidden></a>
<a 
   class="nav-link" 
   [routerLink]="['/einstellungen/kalender']" 
   [queryParams]="{branch: myBranches[0].id}" 
   [class.active]="rla.isActive">
   Kalender verwalten
 </a>

In the component.ts:

withoutQueryParams$: Observable<boolean>;

ngOnInit() {
    this.withoutQueryParams$ = this.route.queryParams.pipe(
        map(params => Object.keys(params).length === 0)
    );
}

In the template.html:

[routerLinkActiveOptions]="{ exact: withoutQueryParams$ | async }"
Related