AngularJS ng-href DirectiveThe ng-href directive should be used instead of href if you have AngularJS code inside the href value. The ng-href directive makes sure the link is not broken even if the user clicks the link before AngularJS has evaluated the code.
Generate an application with routing enabledlink The following command uses the Angular CLI to generate a basic Angular application with an application routing module, called AppRoutingModule , which is an NgModule where you can configure your routes.
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>
Plunkr
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.
An achor should navigate to something, so I guess the behaviour is correct when it routes. If you need it to toggle something on the page it's more like a button? I use bootstrap so I can use this:
<button type="button" class="btn btn-link" (click)="doSomething()">My Link</button>
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