refactor(routerLinkActive): optimised routerLinkActive active check code (#11968)
Modify routerLinkActive to optimise performance by removing unnecessary iteration. By replacing Array.reduce with Array.some, the loop will break when it finds an active link. Useful if used on the parent of a large group of routerLinks. Furthermore, if a RouterLink is active it will not check the RouterLinkWithHrefs.
This commit is contained in:
parent
0286956107
commit
c143fee849
|
@ -109,17 +109,18 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
|
||||||
private update(): void {
|
private update(): void {
|
||||||
if (!this.links || !this.linksWithHrefs || !this.router.navigated) return;
|
if (!this.links || !this.linksWithHrefs || !this.router.navigated) return;
|
||||||
|
|
||||||
const isActiveLinks = this.reduceList(this.links);
|
const isActive = this.hasActiveLink();
|
||||||
const isActiveLinksWithHrefs = this.reduceList(this.linksWithHrefs);
|
|
||||||
this.classes.forEach(
|
this.classes.forEach(
|
||||||
c => this.renderer.setElementClass(
|
c => this.renderer.setElementClass(this.element.nativeElement, c, isActive));
|
||||||
this.element.nativeElement, c, isActiveLinks || isActiveLinksWithHrefs));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private reduceList(q: QueryList<any>): boolean {
|
private isLinkActive(router: Router): (link: (RouterLink|RouterLinkWithHref)) => boolean {
|
||||||
return q.reduce(
|
return (link: RouterLink | RouterLinkWithHref) =>
|
||||||
(res: boolean, link: any) =>
|
router.isActive(link.urlTree, this.routerLinkActiveOptions.exact);
|
||||||
res || this.router.isActive(link.urlTree, this.routerLinkActiveOptions.exact),
|
}
|
||||||
false);
|
|
||||||
|
private hasActiveLink(): boolean {
|
||||||
|
return this.links.some(this.isLinkActive(this.router)) ||
|
||||||
|
this.linksWithHrefs.some(this.isLinkActive(this.router));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue