Since Angular apps are SPAs, the page does not reload when navigating through the application/website. If you happen to scroll to the bottom of the page and clicked a link, the next page will show the content near the bottom too, which is not intended. We need to see the top content so we need a way to scroll to top every time a link is clicked or router changes.
This StackOverflow answer says it all.
So I decided to use the smooth scrolling option and added the option to work with Angular Universal, technically, to not scroll to top when running in the server.
Update Router Outlet
Add an event handler in for your Router Outlet.
<router-outlet (activate)="onActivate($event)"></router-outlet>
Then define the handler in your AppComponent
:
import { Component } from '@angular/core'; import { PLATFORM_ID, APP_ID, Inject } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { constructor( @Inject(PLATFORM_ID) private platformId: Object, @Inject(APP_ID) private appId: string ) {} onActivate(event: any) { if (isPlatformBrowser(this.platformId)) { let scrollToTop = window.setInterval(() => { let pos = window.pageYOffset; if (pos > 0) { window.scrollTo(0, pos - 50); // how far to scroll on each step } else { window.clearInterval(scrollToTop); } }, 16); } } }
That’s it! I increased the scroll speed a bit for my preference.
Amazing thanks!
Good code but what about this? https://stackoverflow.com/questions/39601026/angular-2-scroll-to-top-on-route-change
@Lucas that one does not seem to have animations. I prefer to have animation.
This does not work on Angular 8.
Can this be used on ionic 4 slides?
@Joanne – I have no idea, doesn’t Ionic have the same scrolling utility/feature?
Working in Angular 8
Thanks bro..
Thanks bro! that issue was challenging me