Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Unable to use "scrollPositionRestoration"

Tags:

angular

I am currently using Angular 6.1.5. When the website is routed to a different page, I would like for the page to be scroll back to the top. I tried using { scrollPositionRestoration: 'top' } but it does not work.

Here's my code in app.routing.ts.

export const routing = RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'top' });

Is there an alternative to this? I tried changing from 'top' to enabled' but it does not work as well. I also tried window.scrollTo(0,0); and placed it in ngOnInit() but that doesn't work either.

like image 491
mhfour Avatar asked Sep 01 '25 16:09

mhfour


2 Answers

In my case didn't work because I had this on my CSS.

@media (prefers-reduced-motion: no-preference) {
  :root {
    scroll-behavior: smooth;
  }
}

I changed to

scroll-behavior: auto;

And then it starts working

like image 163
Marc Claramunt Molet Avatar answered Sep 04 '25 05:09

Marc Claramunt Molet


Update the options in your code to provide it with a scrollOffset as well.

export const routing = RouterModule.forRoot(appRoutes, { scrollOffset: [0, 0], scrollPositionRestoration: 'top' });

Another option would be to do it more 'manually'. Here is a StackBlitz demonstrating this approach. Basically in the entry component for the application(or the entry component for the area of your application with the forms) you could subscribe to the router events and on NavigationEnd you can use window.scrollTo

import { Component } from '@angular/core';
import { Router, Event, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent  {
  constructor(
    router: Router
  ) {
    router.events
          .pipe(filter((routerEvent: Event) => routerEvent instanceof NavigationEnd))
          .subscribe(() => window.scrollTo(0, 0));
  }
}
like image 44
peinearydevelopment Avatar answered Sep 04 '25 05:09

peinearydevelopment