When clicking any anchor link which has a href='#'
, the Angular router path
{ path: '', component: NologinComponent, pathMatch: 'full' }
is matched, How should I handle these anchor links so that anchor with href='#'
stays on same page, i.e do nothing.
Example anchor tag
<a class="title-logo" href="#"><img src="/Content/Images/Image1.png"></a>
One More point to consider, i have used the <base href="/" />
in the layout page so that on refresh angular stays on current page and look for the resources from "/" not from inside the current component.
There are a few options:
Option 1:
Override href
attribute with a directive:
@Directive({
selector : '[href]'
})
export class MyLinkDirective {
@Input() href: string;
@HostListener('click', ['$event'])
noop(event: MouseEvent) {
if(this.href.length === 0 || this.href === '#') {
event.preventDefault();
}
}
}
Source
Personally, I like this solution because it is global and angular. Here's a stackblitz example.
Option 2
You can use css and ditch the href
attribute all together:
a {
cursor: pointer;
user-select: none;
}
Then your inactive links would be:
<a class="title-logo"><img src="/Content/Images/Image1.png"></a>
Option 3
CSS pointer-events
:
a.noop {
pointer-events: none;
}
Usage
<a class="title-logo noop" href="#"><img src="/Content/Images/Image1.png"></a>
pointer-events
may cause trouble on some (especially older) browsers, if you care about them. You can see the compatibility list here.
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