refactor(router): RouterLink read urlTree only once (#53817)

In RouterLink, urlTree is created every time we access it, so when used we should read it only once.

PR Close #53817
This commit is contained in:
Ivan Zlatanov
2024-01-06 19:53:50 +02:00
committed by Jessica Janiuk
parent 441a23cb8b
commit 4f7edaa478
2 changed files with 11 additions and 5 deletions
@@ -276,7 +276,9 @@ export class RouterLink implements OnChanges, OnDestroy {
['$event.button', '$event.ctrlKey', '$event.shiftKey', '$event.altKey', '$event.metaKey'])
onClick(button: number, ctrlKey: boolean, shiftKey: boolean, altKey: boolean, metaKey: boolean):
boolean {
if (this.urlTree === null) {
const urlTree = this.urlTree;
if (urlTree === null) {
return true;
}
@@ -296,7 +298,7 @@ export class RouterLink implements OnChanges, OnDestroy {
state: this.state,
info: this.info,
};
this.router.navigateByUrl(this.urlTree, extras);
this.router.navigateByUrl(urlTree, extras);
// Return `false` for `<a>` elements to prevent default action
// and cancel the native behavior, since the navigation is handled
@@ -310,8 +312,9 @@ export class RouterLink implements OnChanges, OnDestroy {
}
private updateHref(): void {
this.href = this.urlTree !== null && this.locationStrategy ?
this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(this.urlTree)) :
const urlTree = this.urlTree;
this.href = urlTree !== null && this.locationStrategy ?
this.locationStrategy?.prepareExternalUrl(this.router.serializeUrl(urlTree)) :
null;
const sanitizedValue = this.href === null ?
@@ -220,7 +220,10 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit
this.routerLinkActiveOptions :
// While the types should disallow `undefined` here, it's possible without strict inputs
(this.routerLinkActiveOptions.exact || false);
return (link: RouterLink) => link.urlTree ? router.isActive(link.urlTree, options) : false;
return (link: RouterLink) => {
const urlTree = link.urlTree;
return urlTree ? router.isActive(urlTree, options) : false;
};
}
private hasActiveLinks(): boolean {