angularangular-routerlink

Angular Routing with Fragment Hash doesn't work if I click the same anchor twice


I am trying to redirect within the page, using a fragment in an anchor tag. It works fine the first time but when I scroll the page up manually and press the anchor link again it doesn't work.

<a class="nav-link page-scroll" [routerLink]="['/']" fragment="home">Home</a>
<a class="nav-link page-scroll" [routerLink]="['/']" fragment="about">About</a>

I have uploaded my code on StackBlitz

Click on About and you will see the page scroll. Scroll up manually and press About again, this time nothing will happen. I'm looking forward to your suggestions on how to fix this.


Solution

  • This happens because you are using the Angular Router to reach the fragment, which dynamically loads the required components client-side, without performing a new request to the server.

    You have 3 possible solutions:

    1. drop the use of the Angular Router, and just use the old plain <a href="#fragment">. Just because there's an Angular way to do it, it doesn't mean that using standard HTML features is forbidden

    2. Don't update the URL, in this way your web application doesn't know if you already clicked the anchor or not, and it will always scroll to the element. You can do it setting the attribute [skipLocationChange]="true", as you can see in this fork of your StackBlitz

    3. Use one of the many solutions provided in this StackOverflow question

    I think that the best solution is the one based on <a href.

    Use the [routerLink] combined with [fragment] when you want to reach the fragment of another route. Not when you want to reach the fragment inside the same route.

    I hope this will be helpful