Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent routerLink action in Angular 2

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?

like image 280
Buckethead Avatar asked Nov 01 '17 15:11

Buckethead


People also ask

How do I stop routerLink?

Angular's standard way to enable/disable navigation from a given route is to implement a CanDeactivate route guard. Similarly, you can implement a CanActivate route guard to enable/disable navigation to a given route.

Can we use href instead of routerLink?

In this case since they are served at two different base urls(in this case for dev environment its localhost:4201 && localhost:4202) using router link will not actually route you to the other base route location. Using href is required or it will fail routing you to the correct url.

What is difference between routerLink and routerLink?

What is the difference between [routerLink] and routerLink ? How should you use each one? They're the same directive. You use the first one to pass a dynamic value, and the second one to pass a static path as a string.

What does routerLink do in angular?

In Angular, RouterLink is a directive for navigating to a different route declaratively. Router. navigate and Router. navigateByURL are two methods available to the Router class to navigate imperatively in your component classes.


2 Answers

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.

like image 195
Yasammez Avatar answered Oct 11 '22 01:10

Yasammez


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
}
like image 24
Vitaliy Alekask Avatar answered Oct 10 '22 23:10

Vitaliy Alekask