Search code examples
angularhrefangular-routingangular-routerangular-routerlink

When should href be used instead of routerLink in Angular?


When I develop in Angular and create views, I always use the routerLink to navigate from one view to another. Recently I have seen important pages made in Angular that use href instead of routerLink to route views on the website. My question is, when is it convenient to use href instead of routerLink in Angular and why? Is it to give the feeling that it is not a SPA?

If so, I do not understand it because it loses the full potential of Angular routing.

Some examples are

https://brandstory.in/
https://www.forbes.com/sites/karstenstrauss/2019/01/22/the-most-sustainable-companies-in-2019/#46dd14376d7d
https://about.google/
https://www.colgate.es/
https://marketingplatform.google.com/intl/es/about/enterprise/

Thanks in advance


Solution

  • When we use href in angular the app loses its state and the entire app gets reloaded. But when we use routerlink the state of the app remains the same E.g. Let's assume you have two pages/component in your angular project named as second and third.

    <div class="nav">
      <p>Using "href"</p>
      <ul>
        <li><a href="/" >1</a></li>
        <li><a href="/second" (click)="onClick($event)">2</a></li>
        <li><a href="/third">3</a></li>
      </ul>
    </div>
    <hr>
    <div class="nav">
      <p>Using "routerLink"</p>
      <ul>
        <li><a routerLink="/">1</a></li>
        <li><a routerLink="/second">2</a></li>
        <li><a routerLink="/third">3</a></li>
      </ul>
    </div>
    <hr>
    <div class="page-content">
      <p>Page Content</p>
      <router-outlet></router-outlet>
      <hr>
      <p>Input Field</p>
      <app-input></app-input>
    </div>
    

    In the above example, if you type something in the input filed and use href navigation to navigate then the state of that will get losses. But when you use routerlink navigation to navigate you will have that input text.

    Let's see what happens behind the screen:-

    <li><a href="/second" (click)="onClick($event)">2</a></li>
    
    onClick(event: Event) {
        event.preventDefault();
      }
    

    if you prevent the default action of href you will see that page will not get reloaded that what happens in routerlink, this simply means that routerlink also used href for navigation but by preventing its default behaviour.