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

When you click on any anchor link that has an href='#'Angular router path

{ path: '', component: NologinComponent, pathMatch: 'full' }

how do I handle these anchor links so that the anchor with href='#'remains on the same page, i.e. nothing to do.

An example tag tag

<a class="title-logo" href="#"><img src="/Content/Images/Image1.png"></a>

I also used one more point to consider <base href="/" />on the layout page, so that when I update Angular I stay on the current page and look for resources from "/" not from inside the current component.

+4
source share
3 answers

There are several options:

Option 1:

Cancel attribute hrefwith directive:

@Directive({
  selector : '[href]',
  host : {
    '(click)' : 'doNothing($event)'
  }
})
export class MyLinkDirective {
  @Input() href: string;

  doNothing(event) {
    if(this.href.length === 0 || this.href === '#') {
      event.preventDefault();
    }
  }
}

Source

, angular. plunker.


2

css href :

a {
  cursor: pointer;
  user-select: none;
}

:

<a class="title-logo"><img src="/Content/Images/Image1.png"></a>

3

CSS pointer-events:

a.noop {
   pointer-events: none;
}

<a class="title-logo noop" href="#"><img src="/Content/Images/Image1.png"></a>

pointer-events ( ) , . .

+7

href='javascript:void(0);'
+3
+1

Source: https://habr.com/ru/post/1674289/


All Articles