Angular, Web Development

Angular 6 – Add scroll to top when route changes

Since Angular apps are SPAs, the page does not reload when navigating through the application/website. If you happen to scroll to the bottom of the page and clicked a link, the next page will show the content near the bottom too, which is not intended. We need to see the top content so we need a way to scroll to top every time a link is clicked or router changes.

This StackOverflow answer says it all.

So I decided to use the smooth scrolling option and added the option to work with Angular Universal, technically, to not scroll to top when running in the server.

Update Router Outlet

Add an event handler in for your Router Outlet.

<router-outlet (activate)="onActivate($event)"></router-outlet>

Then define the handler in your AppComponent:

import { Component } from '@angular/core';
import { PLATFORM_ID, APP_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    @Inject(APP_ID) private appId: string
  ) {}

  onActivate(event: any) {
    if (isPlatformBrowser(this.platformId)) {
      let scrollToTop = window.setInterval(() => {
        let pos = window.pageYOffset;
        if (pos > 0) {
          window.scrollTo(0, pos - 50); // how far to scroll on each step
        } else {
          window.clearInterval(scrollToTop);
        }
      }, 16);
    }
  }
}

That’s it! I increased the scroll speed a bit for my preference.

9 thoughts on “Angular 6 – Add scroll to top when route changes”

Leave a reply

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