DEV Community

Tero Auralinna
Tero Auralinna

Posted on • Originally published at auralinna.blog on

Scroll to the top on Angular route change

By default Angular doesn't scroll to the top of the page when you're navigating to another page. Here is a quick tip 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.

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);
      });
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Inject service into a component

Import the service into the component.

import { ScrollTopService } from '../your/path/scrolltop.service';
Enter fullscreen mode Exit fullscreen mode

Then call the setScrollTop method on ngInit in your component to initialize scrolling.

ngOnInit() {
  this.scrollTopService.setScrollTop();
}
Enter fullscreen mode Exit fullscreen mode

Discussion (1)

Collapse
emertola profile image
emertola

Is this still working?

I have angular app with a blog posts page ('/blog'), where it shows list of blog posts and each has button to redirect the user to that specific blog.
When I tried to click that button ('/blog/'), it doesn't scroll to top. Tried your code, but doesn't work on mine.