Angular 2 scroll to top on route change not working
Wait for the component to initialized component before you start scrolling. So better to put this code under ngAfterViewInit
function.
ngAfterViewInit() {
this.router.events.subscribe((evt) => {
if (!(evt instanceof NavigationEnd)) {
return;
}
window.scrollTo(0, 0)
});
}
The router will emit an event when a new component gets loaded in the <router-outlet>
so you can attach an event to it.
So in your component with <router-outlet>
use:
<router-outlet (activate)="scrollTop($event)">
and then in the same component where you placed <router-outlet>
add the following method:
scrollTop(event) {
window.scroll(0,0);
}