问题描述
我在Angular中使用如下的routerLink
I am using routerLink in Angular as below
<li routerLinkActive="active">
<a [routerLink]="['/view', 10]"
[queryParams]="{'offset': 0, 'numberOfItems': 100}"
queryParamsHandling="merge">
<div>View</div>
<div><span class="badge" [innerHtml]="viewCount"></span></div>
</a>
</li>
因此,URL看起来像.active类已添加到li标记中
So the .active class was added to li tag when the URL looks like
/view/10?offset=0&numberOfItems=100
如果将URL更改为offset
或numberOfItems
的其他值,则将删除.active类,例如.
If the URL was changed either offset
or numberOfItems
to a different value, the .active class will be removed, such as.
/view/10?offset=0&numberOfItems=120
我查看了角度文档,并设法通过添加另一个routerLink使它工作,但是隐藏如下.
I went through the angular docs and managed to make it works by adding another routerLink but make it hidden as below.
<li routerLinkActive="active">
<a [routerLink]="['/view', 10]"
[queryParams]="{'offset': 0, 'numberOfItems': 100}"
queryParamsHandling="merge">
<div>View</div>
<div><span class="badge" [innerHtml]="viewCount"></span></div>
</a>
<a [routerLink]="['/view', 10]" style="display:none;">
<div><span class="badge" [innerHtml]="viewCount"></span></div>
</a>
</li>
似乎上述方法有点破绽.当路由器参数与可选查询参数一起出现时,是否可以进行任何配置以使routerLinkActive正常工作?
Seem the above approach is a little hack. Is there any configuration that I can set to make routerLinkActive works when router parameter presents with optional query parameter?
推荐答案
您可能会发现这很有用-扩展RouterLinkActive-如果项目包含字符串,则该项目被选中" ...
You may find this helpful - extend RouterLinkActive - an item is 'selected' if it contains a string...
import { Directive, Input, OnChanges, ElementRef, Renderer2, ChangeDetectorRef, SimpleChanges, Injector, AfterContentInit } from '@angular/core';
import { Router,RouterLinkActive, RouterLink, RouterLinkWithHref } from '@angular/router';
@Directive({
selector: '[routerLinkActiveQS]',
exportAs: 'routerLinkActiveQS'
})
export class RouterLinkQsactiveDirective extends RouterLinkActive implements OnChanges, AfterContentInit
{
@Input()
set routerLinkActiveQS(data: string[]|string) {
(<any>this).routerLinkActive = data;
}
@Input() routerLinkActiveQSContains : string;
constructor ( injector: Injector ) {
super ( injector.get(Router),injector.get(ElementRef),injector.get(Renderer2),injector.get(ChangeDetectorRef));
(<any>RouterLinkQsactiveDirective.prototype).isLinkActive = this.MyisLinkActive;
}
ngOnChanges(changes: SimpleChanges): void {
super.ngOnChanges(changes);
}
ngAfterContentInit(): void {
super.ngAfterContentInit();
}
private MyisLinkActive(router: Router): (link: (RouterLink|RouterLinkWithHref)) => boolean {
const result = (link: RouterLink | RouterLinkWithHref) => {
let resultInsde = router.isActive(link.urlTree, this.routerLinkActiveOptions.exact);
resultInsde = resultInsde || router.url.includes ( this.routerLinkActiveQSContains );
return resultInsde;
}
return result;
}
}
这篇关于Angular-routerLinkActive和queryParams处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!