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:
Connor Wyatt 2016-09-30 17:42:54 +01:00 committed by Chuck Jazdzewski
parent 0286956107
commit c143fee849
1 changed files with 10 additions and 9 deletions

View File

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