Wednesday, 27 December 2017

Angular 2 Scroll to top on Route Change

Many of us encounter with a problem of side scroll bar is not being on the top on routing or while navigating to other page.

This problem is solved just by using

         window.scrollTo(0,0);

In your main.ts file(means your global typescript file), within ngOnInIt() function at the top.



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() {
        
       window.scrollTo(0, 0);<!--this should be the first line of this function -->
    }
}

No comments:

Post a Comment