Prevent routerLink action in Angular 2
Asked Answered
H

2

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?

Hoarfrost answered 1/11, 2017 at 15:4 Comment(7)
instead of event.preventDefault, pls try return false;Electron
@VeenaK.Suresh doesn't work (Hoarfrost
do you really need routerLink="/test" in your anchor (<a>) tag? if u can remove it from there and add the routing in your testClick() else statement, i hope then it will work.Electron
@VeenaK.Suresh unfortunately I do, because I need to have a possibility to open this link in new tab, but if a link doesn't have a routerLink attribute, a browser doesn't "parse" it as a link.Hoarfrost
I have the same issue. Any solution?Otte
@Timtest, I've written custom routerLink directive. For me it works.Hoarfrost
Possible duplicate of Is it possible to stop router navigation based on some conditionPantechnicon
C
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
}
Claudie answered 22/1, 2018 at 14:15 Comment(5)
$event.preventDefault() should be shown in your handler tooDennis
span does not have any default handler of click event, so you have not to prevent it.Claudie
you are right, but in this case you have to prevent, or it will not work as expected @VitaliyAlekaskDennis
Working solution. In case you are using Material Buttons, take care of the click area. You have to remove the padding of the anchor element and set it to the inner span element + "display block" (for height)Stettin
With that solution using the keyboard to trigger a link may still worksCervelat
F
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.

Finable answered 26/11, 2019 at 16:55 Comment(1)
this is the only solution that actually worked, and i searched allot, thank you!Personalty

© 2022 - 2024 — McMap. All rights reserved.