Reputation: 223
I have a link:
<a routerLink="/test" (click)="testClick($event)">Test link </a>
I wanted to do in testClick
function something like this:
testClick(event:any) {
if (..some expression..) {
//custom popup confirmation
//if true --> event.preventDefault();
} else {
// go to link
}
}
But calling preventDefault
doesn't work. How can I fix it?
Upvotes: 11
Views: 10180
Reputation: 1551
There is an issue for this on github: https://github.com/angular/angular/issues/21457
In the meantime, you can help yourself with putting some more logic into the routerLink directive:
<a [routerLink]="someExpression ? [] : '/test'" (click)="testClick()">Test link</a>
This way you need to handle your expression twice: once in the link and once in the code; but on the other hand you don't have to care about the event at all, since it will propagate normally but the router will simply ignore it.
Upvotes: 3
Reputation: 351
You can wrap your link's text with span element and bind event handler on this span:
<a routerLink="/test"><span (click)="testClick($event)">Test link</span></a>
And your handler:
function testClick($event: MouseEvent) {
if (expression) {
$event.stopPropagation();
// do something
return;
}
// navigates to /test
}
Upvotes: 13