Angular 2 scroll to top on route change not working
The router will emit an event when a new component gets loaded in the so you can attach an event to it.
So in your component with use:
and then in the same component where you placed add the following method:
scrollTop[event] { window.scroll[0,0]; }Wait for the component to initialized component before you start scrolling. So better to put this code under ngAfterViewInit function.
This similar issue was faced by me which was due to the style applied to body. i.e.
body { height: 100%; overflow-x: hidden; }If I removed this style then my layout was badly affected.
Instead of removing style I tried below solution and it worked for me...
Solution:
export class AppComponent implements OnInit { constructor[private router: Router, private changeDetect: ChangeDetectorRef] { } ngOnInit[] { this.router.events.subscribe[[evt] => { if [![evt instanceof NavigationEnd]] { return; } // Change height:100% into auto $['body'].css['height', 'auto']; // Successfully scroll back to top $['body'].scrollTop[0]; // Remove javascript added styles $['body'].css['height', '']; this.changeDetect.detectChanges[]; }]; } }