In Angular 1.x I can do the following to create a link which does basically nothing:
My Link
But the same tag
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>
Here are some ways to do it:
<a href="" (click)="false">Click Me</a>
<a style="cursor: pointer;">Click Me</a>
<a href="javascript:void(0)">Click Me</a>
A really simple solution is not to use an A tag - use a span instead:
<span class='link' (click)="doSomething()">Click here</span>
span.link {
color: blue;
cursor: pointer;
text-decoration: underline;
}
You have prevent the default browser behaviour. But you don’t need to create a directive to accomplish that.
It’s easy as the following example:
my.component.html
<a href="" (click)="goToPage(pageIndex, $event)">Link</a>
my.component.ts
goToPage(pageIndex, event) {
event.preventDefault();
console.log(pageIndex);
}
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>