Auralinna.blog - Tero Auralinna's web development blogAuralinna.blogTero Auralinna's blog about intriguing world of web development. Tweaking pixels since the '90s.

Scroll to the top on Angular route change

Published: 1/16/2018

By default, Angular doesn't scroll to the top of the page when you're navigating to another page. Here is a quick tip on how to implement scrolling.

Implement a scroll service

At first, create a new service called ScrollTopService. On a server side (Angular Universal) we don't need this "hack" so it's limited only to a browser.

scrolltop.service.ts

import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { isPlatformBrowser } from '@angular/common';

@Injectable()
export class ScrollTopService {

  constructor(
    @Inject(PLATFORM_ID) private platformId: Object,
    private router: Router) { 
  }

  setScrollTop() {
    if (isPlatformBrowser(this.platformId)) {
      this.router.events.subscribe((event: NavigationEnd) => {
        window.scroll(0, 0);
      });
    }
  }
}

Register the service by adding it into app.module.ts

import { ScrollTopService } from 'your/path/scrolltop.service';

@NgModule({
  ...
  providers: [
    ScrollTopService,
    ...
  ]
})

Inject the service into a component

Inject new service into a component and then call the setScrollTop method on ngInit to initialize scrolling.

Example app.component.ts

import { 
  Component, 
  OnInit 
} from '@angular/core';

import { ScrollTopService } from 'your/path/scrolltop.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {

  constructor(
    private scrollTopService: ScrollTopService
  ) {}

  ngOnInit() {
    this.scrollTopService.setScrollTop();
  }
}

Edited on 11th of June, 2019

Be the first commenter?

Latest CodePens

I am an experienced web developer with an eye for solid UI/UX design. I have specialized in front-end development, responsive web design, design systems, modern web frameworks, and content management systems. I also have experience in mobile apps development and back-end coding with PHP, Node.js, and Java. So I have a full stackish background, but I'm enjoying most building robust and beautiful front-ends with performance, accessibility, and testability in mind.

© Tero Auralinna

Auralinna.fiSunset with Bubbles: Travel and Photography Blog

The icon "ellipsis" is provided by loading.io