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

828
Visualizações
anchor href vs angular routerlink

I am trying to use anchor tag with href in my Angular 7 app. When I click on the link the url changes in the browser but the page doesn't get navigated to. It works if I put target="_self" so this works

<a href="/abcd" target="_self">Abcd</a>

but this does not work only the url changes in the browser but nothing happens

<a href="/abcd">Abcd</a>

where as if I use Angular routing and use RouterLink it works.

<a routerLink="/abcd" routerLinkActive="active">Abcd</a>

Can anyone explain the behaviour please.

over 4 years ago · Santiago Trujillo
7 Respostas
Responde à pergunta

0

Using href directly tells the browser to open the link as a new, such that the app will be reloaded and still linked to the exact page that it has been configured for.

Based on the doc, routerLink navigates the app without reloading using the internal api.

you could click the link that uses href and routerLink to see the difference demo

over 4 years ago · Santiago Trujillo Relatório

0

Angular applications are Single Page Applications (SPA). Using href breaks that design pattern. The effect is that each navigation that utilises href completely resets your application state. Always avoid href when using Angular or any other SPA.

routerLink loads resources internal to Angular, and the page that loaded in the browser is never completely reloaded (and so app state is maintained.) A clue to this being the case is the browser's loading indicator:

When traditional links are followed, you'll see in your browser the spinner going (on the tab, or by the address bar in most cases.) When you're waiting for Angular components to load, that spinner will be idle.

It's something I always check when developing, when my state resets. Sometimes the problem is that I used href instead of routerLink.

over 4 years ago · Santiago Trujillo Relatório

0

Navigating using href:

href is the default attribute provided by browsers for navigating (switching) between pages, where the entire page will be get re-loaded losing the current state.

whereas the hack is by preventing the default behavior.

for example:

Inside template:

 <a href="route" (click)=onClick($event) />

Inside Component:

onClick(event :Event){
    event.preventDefault();
}

Using the target attribute in href:

Please refer to https://www.w3schools.com/tags/att_link_target.asp

Navigating using routerLink:

Angular mimics the above behaviour inside routerLink directive

over 4 years ago · Santiago Trujillo Relatório

0

If your using href in angular app then avoid it. Angular has router feature where routerLink is part of that.

<p routerLink='/path'>Text</p>

For more understanding check this article Angular Routing

over 4 years ago · Santiago Trujillo Relatório

0

Bytech has a correct answer but there is a case when you would want to use href in angular. For instance I have a single application that has multiple projects in it. On a link I want to navigate from the store project to the member portal project. In this case since they are served at two different base urls(in this case for dev environment its localhost:4201 && localhost:4202) using router link will not actually route you to the other base route location. Using href is required or it will fail routing you to the correct url.

over 4 years ago · Santiago Trujillo Relatório

0

Sometimes you can't use routerLink, if for example, you are in a non angular web component.

A workaround that I used to get around the refresh problem was to check all "a" tag clicks and prevent the default behaviour if a routerlink attribute wasn't present and then use the router to navigate.

  @HostListener('window:click', ['$event'])
  onClick(e: any) {
    const path = e.composedPath() as Array<any>;
    const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
    if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
      const href = firstAnchor.getAttribute('href');

      this.router.navigateByUrl(href);

      e.preventDefault();
    }
  }
over 4 years ago · Santiago Trujillo Relatório

0

Href is the basic attribute provided by Html to navigate through pages which reloads the page on click.

routerLink is the attribute provided by angular to navigate to different components without reloading the page.

Major difference between both is that href kills the state of the current page where routerLink doesnt lose the state of the page.

For Eg. if an input text box is present in the page, the routerLink will retains its value after navigation.The routerLink can be considered as the custom attribute of href in angular by overriding some of the features like Page reloading

over 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