Scroll to top issue in Angular apps

During my 1.5+ years of experience with various versions of Angular, there is this one thing that haunts pretty much every developer while working with Angular apps i.e. default scroll to top.

While switching between different routes in an Angular app, the app somewhat stores the scroll position. This might be a use case with some apps but 99% of the apps require scroll to reset to top while switching routes.

There are two ways in which you can achieve this.

  1. Calling a utility function that resets the scroll every-time the route changes
  2. Doing it the Angular way

The “scrollPositionRestoration” flag

The scrollPositionRestoration flag helps to resets the scroll position once the route changes. To globally apply this flag, one can use app-routing.module.ts

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

const routes: Routes = [];

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

The flag configures if the scroll position needs to be restored when navigating back.

It has 3 values:

  1. disabled– (Default) Does nothing. The scroll position is maintained on navigation. That is the reason the page does not reset to top.

  2. enabled – This is a bit tricky:
    a. It restores the previous scroll position on backward navigation
    b. It scrolls to top i.e [0,0] of the page in forward navigation
    c. It restores to anchor (<a></a>) tag on backward navigation (if any)

  3. top: Always restore the page to [0,0] i.e top in forward and backward navigation

The scrollPositionRestoration flag is part of the ExtraOptions of @angular/router


Share it with your friends, colleagues, and other Angular developers!

You can reach out to me through the Contact Form on this blog, the comments section below, or hit me up on twitter – @secondbestcoder

Leave a Reply

Your email address will not be published. Required fields are marked *