Angular 10 scroll to top on route change

When I first picked up Angular many years ago, one of the more frustrating aspects was that on using the router to navigate to another page, the scroll position was kept. This meant you were taken to the new page, but you would be scrolled halfway down the page [Or often right at the bottom if you were filling out a form].

Back then, you had all sorts of crazy fixes involving listening for router events, or maybe even manually scrolling the page. So recently when I ran into the issue on a new project I hoped things had changed. And they have, sort of. I mean, the issue is still there but there is a slightly more elegant fix.

When registering your router module [Typically a new Angular project created using the CLI will have an app-routing.module.ts], you can now edit your import as follows :

RouterModule.forRoot[routes, {scrollPositionRestoration: 'enabled'}]

In future versions of Angular, its hoped that this will become the default [Certainly there would be far more use cases of scrolling to the top over keeping the same position], but as of writing you still manually need to add the scrollPositionRestoration param.

Note that this was introduced sometime in Angular 6, for earlier versions [Which hopefully you arent creating new projects on], you will still need to do the old school subscribe method. To do this, you need to modify your main component [Often your AppComponent] to subscribe to the router event of NavigationEnd and then call scroll.

export class AppComponent implements OnInit { private router : Router; constructor [router : Router] { this.router = router; } ngOnInit[] { this.router.events.subscribe[x => { if[x instanceof NavigationEnd] { window.scrollTo[0, 0]; } }]; } }

Again this is required only if you are running a version of Angular before 6!

Related Posts

  1. Angular Directive To Limit Text Input
  2. How To Resolve Type EventEmitter Is Not Generic Error
  3. Understanding Pure vs Impure Pipes In Angular
  4. Better Constructor Overloading In Typescript/Angular

Video liên quan

Chủ Đề