Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

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.

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report

0

Try this

href='javascript:void(0);'
about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!