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.
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
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With