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

I am an experienced web developer with an eye for a solid UI/UX design. I have specialized in front-end development, responsive web design, 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 am a Full Stackish web developer with a strong passion for a beautiful front-end.

Scroll to the top on Angular route change

16.01.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 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);
      });
    }
  }
}

Inject service into a component

Import the service into the component.

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

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

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

Latest blog posts

Latest CodePens

View all CodePens