Angular 2 Scroll to top on Route Change

Naveed Ahmed picture Naveed Ahmed · Sep 20, 2016 · Viewed 171.8k times · Source

In my Angular 2 app when I scroll down a page and click the link at the bottom of the page, it does change the route and takes me the next page but it doesn't scroll to the top of the page. As a result, if the first page is lengthy and 2nd page has few contents, it gives an impression that the 2nd page lacks the contents. Since the contents are visible only if user scroll to the top of the page.

I can scroll the window to the top of the page in ngInit of the component but, is there any better solution that can automatically handle all routes in my app?

Answer

Guilherme Meireles picture Guilherme Meireles · Sep 20, 2016

You can register a route change listener on your main component and scroll to top on route changes.

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

@Component({
    selector: 'my-app',
    template: '<ng-content></ng-content>',
})
export class MyAppComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() {
        this.router.events.subscribe((evt) => {
            if (!(evt instanceof NavigationEnd)) {
                return;
            }
            window.scrollTo(0, 0)
        });
    }
}