Scroll to top on navigation in Angular

November 4th 2022 Angular

In Angular applications with default routing options, the scroll position is not reset when you navigate between pages. If you scroll down on the source page and click a link there, the target page opens at the same scroll position. We are not used to such behavior when browsing the Internet. We expect the target page to scroll all the way to the top.

Fortunately, there is a router option that changes this behavior - scrollPositionRestoration:

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { scrollPositionRestoration: "enabled" }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}

According to the reference documentation, this behavior will be set by default in a future release of Angular. This is not yet the case in the current version 14, although the option was originally introduced in version 6. A possible reason for this could be the fact that the feature still does not work reliably, especially the part about restoring the previous scroll position when navigating.

You can check the effect of this option in an example project from my GitHub repository. It consists of two pages with links to each other. The last commit has the option enabled. The commit before it uses the default options.

If you do not like Angular's default behavior of maintaining scroll position when you navigate to a new page, try enabling the scrollPositionRestoration router option. In version 14, it still does not reliably deliver what the documentation promises, but it might work well enough for you if you just want to reset the scroll position when navigating to a page.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Copyright
Creative Commons License