How to use “routerLinkActive” with query params in Angular 6?

不问归期 提交于 2020-05-14 16:31:05

问题


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>

回答1:


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



回答2:


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>


来源:https://stackoverflow.com/questions/52037979/how-to-use-routerlinkactive-with-query-params-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!