Search code examples
angularscrollangular-routerlink

Angular scroll top after route changes interfere with relative url changes


I have enabled the scrollPositionRestoration in my app-routing module as it follows:

imports: [RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' })]

But this creates conflicts when I try to make the user scroll to the page with routerLink, here's an example:

<li><a routerLink="/" fragment='servizi'>{{ "NAV_SERVIZI" | translate }}</a></li>

When the user clicks on the link, the url is compiled correctly: www.website.com/#servizi, while the user's redirect on the top of the page instead of at the middle, where the #servizi element is.

How can I enable the scrollPositionRestoration behavior only for page changes while preserving normal scrolling when I redirect the user within the same page?


Solution

  • You can set anchorScrolling: 'enabled'

    imports: [RouterModule.forRoot(routes, { 
      anchorScrolling: 'enabled',
      scrollPositionRestoration: 'enabled' 
    })]
    

    https://angular.io/api/router/InMemoryScrollingOptions#anchorScrolling