Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, handle anchor links with href='#'

Tags:

angular

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.

like image 499
Vinay Pratap Singh Bhadauria Avatar asked Apr 07 '17 10:04

Vinay Pratap Singh Bhadauria


2 Answers

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.

like image 136
s.alem Avatar answered Sep 27 '22 20:09

s.alem


Try this

href='javascript:void(0);'
like image 43
Pramod Patil Avatar answered Sep 27 '22 21:09

Pramod Patil