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?
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.
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 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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With