Angular routerLinkActiveOptions

左心房为你撑大大i 提交于 2020-01-16 19:30:15

问题


I have some link like this

<li routerLinkActive="active" class="nav-item">
<a [routerLink]="['contracts']" 
[queryParams]="{ activeOnly: false }" 
class="nav-link">Contracts</a>
</li>

You see here in params i have ?activeOnly=false with this approach all is ok when my url is like

contracts?activeOnly=false active css class is added in html and user can see that it is active link

The problem I have that sometimes url can be changed like this contracts?activeOnly=true&id=1 then active css does not apply anymore.

What i need is to have active css class on element even if url has changed with query params.

Example if url is like this contracts?activeOnly=true&id=1

active css class must also stay on LI html tag


回答1:


RouterLinkActive if used with queryParams needs to be an exact match, So the above solution will not work. There was a proposal to make routeLinkActiveOptions but was dropped by Angular team.

You can define your own method to identify active.

Here in the below snippet I am defining a method is link active will return true if the path url minus any query params matches the routerlink path passed from template.

import {Router} from '@angular/router';

constructor(private router: Router){

}

isLinkActive(link) {
  const url = this.router.url;
  return link.id === url.substring(1, url.indexOf('?'));
}

From the template assign class="active" if the method isLinkActive returns true

<li *ngFor="let link of links" [class.active]="isLinkActive(link)">
  <a [routerLink]="'/'+link.id" [queryParams]="{ activeOnly: false }">{{link.name}}</a>
</li>

Stackblitz : https://stackblitz.com/edit/angular-8f7jk8



来源:https://stackoverflow.com/questions/57955575/angular-routerlinkactiveoptions

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