Auto Scroll To The Top Of The Page On Route Change

When I first picked up Angular many years ago, one of the more frustrating aspects was that on using the router to navigate to another page, the scroll position was kept. This meant you were taken to the new page, but you would be scrolled halfway down the page (Or often right at the bottom if you were filling out a form).

Back then, you had all sorts of crazy fixes involving listening for router events, or maybe even manually scrolling the page. So recently when I ran into the issue on a new project I hoped things had changed. And they have, sort of. I mean, the issue is still there but there is a slightly more elegant fix.

When registering your router module (Typically a new Angular project created using the CLI will have an app-routing.module.ts), you can now edit your import as follows  :

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

In future versions of Angular, it’s hoped that this will become the default (Certainly there would be far more use cases of scrolling to the top over keeping the same position), but as of writing you still manually need to add the scrollPositionRestoration param.

Note that this was introduced sometime in Angular 6, for earlier versions (Which hopefully you aren’t creating new projects on), you will still need to do the old school subscribe method. To do this, you need to modify your main component (Often your AppComponent) to subscribe to the router event of NavigationEnd and then call scroll.

export class AppComponent implements OnInit  {
  private router : Router;

  constructor (router : Router)
  {
    this.router = router;
  }

  ngOnInit() {
    this.router.events.subscribe(x => {
      if(x instanceof NavigationEnd)
      {
        window.scrollTo(0, 0);
      }
    });
  }
}

Again this is required only if you are running a version of Angular before 6!

Leave a Reply

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