8

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.

4 Answers4

15

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.

s.alem
  • 12,579
  • 9
  • 44
  • 72
6

Try this

href='javascript:void(0);'
Pramod Patil
  • 2,704
  • 2
  • 14
  • 20
1

Since adding this functionality is tricky, I suggest you to not reinvent the wheel, take a look at ng2-page-scroll.

If you'd like to investigate more, you should read the Router & Navigation Guide.

  • i am not making the page scrolls, the problem is simply with any click for which a link is not defined. – Vinay Pratap Singh Bhadauria Apr 19 '17 at 08:38
  • in that case you can't use anchor links. If you need something to trigger on click, you must use the [click event](https://angular.io/docs/ts/latest/guide/user-input.html#!#sts=src%2Fapp%2Fclick-me.component.ts). When you build something with Angular, you need to have in mind that you're not creating a simple html static page. –  Apr 19 '17 at 11:00
-1

The sample way could be adding this piece of code event.preventDefault(); inside your event function ..

such as

function fn(event) { event.preventDefault(); ...
}

Damon Wu
  • 57
  • 4