Scroll to top of page in Angular 2 (Using routing)


Sometime we need to move on next page using clicking on page bottom link.

In Angular 2 there is a problem. Next page will not move directly to the top of the page.

This may give bad impression to end user.

Below is one way to move focus on top of the page.

register a listener of route change on main component and scroll to 

top on route changes.

Shown in below example.


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

    selector: 'main-app',
    template: '',

export class MainComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() { => {
            if (!(evt instanceof NavigationEnd)) {
            window.scrollTo(0, 0)

You can also used document.body.scrollTop = 0. 

 Hope this will helpful.

Posted in Labels: |


Post a Comment