Disabling routerLink with stopImmediatePropagation method
There is no solution that would lead to this markup <a routerLink="" attributeSelectorForComponent></a>
.
The solution you tried won't work because stopImmediatePropagation
is meant to prevent the event from bubbling, and preventDefault
is meant to prevent the default browser behavior for this type of event (e.g: submit event will trigger a POST
request). In either case, Angular will be notified of the event and will react accordingly.
A clean solution would have been possible if the RouterLink
directive had a exportAs
attribute. In that case, it would have been possible to control the RouterLink
from a custom directive. Unfortunately, that is not the case (RouterLink source)
The only option left is to extend the RouterLinkWithHref
directive like this:
@Directive({
selector: "a[myRouterLink],area[myRouterLink]"
})
export class MyDirective extends RouterLinkWithHref implements OnChanges {
@Input()
myRouterLink;
@Input()
myDisabled;
constructor(
private myRouter: Router,
private myRoute: ActivatedRoute,
private myLocationStrategy: LocationStrategy,
private host: ElementRef
) {
super(myRouter, myRoute, myLocationStrategy);
}
ngOnChanges() {
if (this.myDisabled) {
this.host.nativeElement.setAttribute("disabled", "disabled");
this.routerLink = null;
} else {
this.host.nativeElement.removeAttribute("disabled");
this.routerLink = this.myRouterLink;
}
}
}
This gives the following markup: <a myRouterLink="a" [myDisabled]="disabled"></a>
Note that for a full working solution, you would have to also extend RouterLink
You can try the demo here: https://stackblitz.com/edit/angular-p2w4ff