You can access routerLink instance by injecting RouterLinkWithHref in the directive.
Directive:
import { ElementRef, Optional, Input, Directive, OnChanges } from '@angular/core';
import { RouterLinkWithHref } from '@angular/router';
@Directive({
selector: '[externalLink]'
})
export class ExternalLinkDirective implements OnChanges {
@Input() externalLink: string;
constructor(
private el: ElementRef,
@Optional() private link: RouterLinkWithHref
) {}
ngOnChanges(){
if (!this.link || !this.externalLink) {
return;
}
this.el.nativeElement.href=this.link.href=this.externalLink;
// Replace onClick
this.link.onClick = (...args: any[]) => {
return true;
}
}
}
Usage:
Link