'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 1:[1]
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:
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 forbiddenDon'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 StackBlitzUse 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
Solution 2:[2]
Even though this thread is old, I just had the same problem.
I think you just missed the scroll settings in the app-routing.module.ts
Solution:
change your navigation code to this:
<a class="nav-link page-scroll"routerLink="/" fragment="home">Home</a>
<a class="nav-link page-scroll"routerLink="/" fragment="about">About</a>
and add the following to your app.routing.module.ts:
@NgModule({
imports: [RouterModule.forRoot(routes,
{
scrollPositionRestoration: 'enabled',
anchorScrolling: 'enabled',
onSameUrlNavigation: 'reload',
scrollOffset: [0, 50],
relativeLinkResolution: 'legacy',
})],
exports: [RouterModule]
})
export class AppRoutingModule { }
you have to enable anchorScrolling and scrollPositionRestoration. You can also add other settings here such as a scroll offset.
Hopefully it helps someone!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cristian Traìna |
Solution 2 | J L |