In Angular 1.x I can do the following to create a link which does basically nothing:
My Link
But the same tag
Updated for Angular2 RC4:
import {HostListener, Directive, Input} from '@angular/core';
@Directive({
selector: '[href]'
})
export class PreventDefaultLinkDirective {
@Input() href;
@HostListener('click', ['$event']) onClick(event) {this.preventDefault(event);}
private preventDefault(event) {
if (this.href.length === 0 || this.href === '#') {
event.preventDefault();
}
}
}
Using
bootstrap(App, [provide(PLATFORM_DIRECTIVES, {useValue: PreventDefaultLinkDirective, multi: true})]);
you need to prevent event's default behaviour as follows.
In html
<a href="" (click)="view($event)">view</a>
In ts file
view(event:Event){
event.preventDefault();
//remaining code goes here..
}
I have 4 solutions for dummy anchor tag.
1. <a style="cursor: pointer;"></a>
2. <a href="javascript:void(0)" ></a>
3. <a href="current_screen_path"></a>
4.If you are using bootstrap:
<button class="btn btn-link p-0" type="button" style="cursor: pointer"(click)="doSomething()">MY Link</button>
I wonder why no one is suggesting routerLink and routerLinkActive (Angular 7)
<a [routerLink]="[ '/resources' ]" routerLinkActive="currentUrl!='/resources'">
I removed the href and now using this. When using href, it was going to the base url or reloading the same route again.
simeyla solution:
<a href="#" (click)="foo(); false">
<a href="" (click)="false">
Updated for Angular 5
import { Directive, HostListener, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector : '[href]'
})
export class HrefDirective {
@Input() public href: string | undefined;
@HostListener('click', ['$event']) public onClick(event: Event): void {
if (!this.href || this.href === '#' || (this.href && this.href.length === 0)) {
event.preventDefault();
}
}
}