Created
October 11, 2023 19:13
-
-
Save eneajaho/e3ed8c09ddd2654b434b72a2af385c80 to your computer and use it in GitHub Desktop.
Router Link with external + internal links
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Directive({ | |
selector: 'a[mnLink]', | |
standalone: true, | |
hostDirectives: [ | |
{ | |
directive: RouterLink, | |
inputs: [ | |
'queryParams', 'queryParamsHandling', | |
'state', 'fragment', 'target' | |
], | |
}, | |
], | |
}) | |
export class MnLink implements OnChanges { | |
private renderer = inject(Renderer2); | |
private elRef: ElementRef<HTMLAnchorElement> = inject(ElementRef); | |
private routerLinkRef = inject(RouterLink); | |
@Input() mnLink: string | null | undefined; | |
ngOnChanges() { | |
if (!this.mnLink) { | |
this.routerLinkRef.routerLink = null; | |
this.applyAttributeValue('href', null); | |
return; | |
} | |
try { | |
const urlObj = new URL(this.mnLink); | |
this.applyAttributeValue('href', urlObj.toString()); | |
} catch { | |
this.routerLinkRef.routerLink = this.mnLink; | |
this.routerLinkRef.ngOnChanges({}); | |
} | |
} | |
private applyAttributeValue(attrName: string, attrValue: string | null) { | |
const el = this.elRef.nativeElement; | |
if (attrValue !== null) { | |
this.renderer.setAttribute(el, attrName, attrValue); | |
} else { | |
this.renderer.removeAttribute(el, attrName); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment