Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

Try this

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

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda