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:

committed by
Chuck Jazdzewski

parent
b39d3a173e
commit
3ee8c75eff
@ -109,17 +109,18 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
|
||||
private update(): void {
|
||||
if (!this.links || !this.linksWithHrefs || !this.router.navigated) return;
|
||||
|
||||
const isActiveLinks = this.reduceList(this.links);
|
||||
const isActiveLinksWithHrefs = this.reduceList(this.linksWithHrefs);
|
||||
const isActive = this.hasActiveLink();
|
||||
this.classes.forEach(
|
||||
c => this.renderer.setElementClass(
|
||||
this.element.nativeElement, c, isActiveLinks || isActiveLinksWithHrefs));
|
||||
c => this.renderer.setElementClass(this.element.nativeElement, c, isActive));
|
||||
}
|
||||
|
||||
private reduceList(q: QueryList<any>): boolean {
|
||||
return q.reduce(
|
||||
(res: boolean, link: any) =>
|
||||
res || this.router.isActive(link.urlTree, this.routerLinkActiveOptions.exact),
|
||||
false);
|
||||
private isLinkActive(router: Router): (link: (RouterLink|RouterLinkWithHref)) => boolean {
|
||||
return (link: RouterLink | RouterLinkWithHref) =>
|
||||
router.isActive(link.urlTree, this.routerLinkActiveOptions.exact);
|
||||
}
|
||||
|
||||
private hasActiveLink(): boolean {
|
||||
return this.links.some(this.isLinkActive(this.router)) ||
|
||||
this.linksWithHrefs.some(this.isLinkActive(this.router));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user