Prevent routerLink action in Angular 2

Buckethead picture Buckethead · Nov 1, 2017 · Viewed 7.4k times · Source

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?

Answer

Vitaliy Alekask picture Vitaliy Alekask · Jan 22, 2018

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
}