11

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?

Antti29
  • 2,953
  • 12
  • 34
  • 36
Buckethead
  • 213
  • 5
  • 14

2 Answers2

13

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
}
Vitalii Alekask
  • 341
  • 3
  • 7
3

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.

Yasammez
  • 1,383
  • 12
  • 15