Passive Link in Angular 2 - <a href=""> equivalent
If you have Angular 5 or above, just change
<a href="" (click)="passTheSalt()">Click me</a>
into
<a [routerLink]="" (click)="passTheSalt()">Click me</a>
A link will be displayed with a hand icon when hovering over it and clicking it won't trigger any route.
Note: If you want to keep the query parameters, you should set queryParamsHandling
option to preserve
:
<a [routerLink]="" queryParamsHandling="preserve" (click)="passTheSalt()">Click me</a>
That will be same, it doesn't have anything related to angular2
. It is simple html tag.
Basically a
(anchor) tag will be rendered by HTML parser.
Edit
You can disable that href
by having javascript:void(0)
on it so nothing will happen on it. (But its hack). I know Angular 1 provided this functionality out of the box which isn't seems correct to me now.
<a href="javascript:void(0)" >Test</a>
Other way around could be using, routerLink
directive with passing ""
value which will eventually generate blank href=""
<a routerLink="" (click)="passTheSalt()">Click me</a>
There are ways of doing it with angular2, but I strongly disagree this is a bug. I'm not familiarized with angular1, but this seems like a really wrong behavior even though as you claim is useful in some cases, but clearly this should not be the default behavior of any framework.
Disagreements aside you can write a simple directive that grabs all your links and check for href
's content and if the length of it it's 0 you execute preventDefault()
, here's a little example.
@Directive({ selector : '[href]', host : { '(click)' : 'preventDefault($event)' }})class MyInhertLink { @Input() href; preventDefault(event) { if(this.href.length == 0) event.preventDefault(); }}
You can make it to work across your application by adding this directive in PLATFORM_DIRECTIVES
bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: MyInhertLink, multi: true})]);
Here's a plnkr with an example working.