I was building a basic Angular application, I have a few components, from my home page when I go to out services page, and scroll down, and go back to home page, the scroll is set to bottom of page.
I would like to set my scroll to top every time i open up a component.
Since I am using angular7 I tried using the option available in router,
{scrollPositionRestoration : 'enabled'}
then
{scrollPositionRestoration : 'top'}
,
but it didn't work on Chrome nor on Chrome mobile or on Edge.
Other than that, I tried to set a listener on router and using
window.scrollTop(0,0)
, that didn't work either, neither did using the document variable.
I just want my scroll bar at top. Its such a naive thing but it has frustrated me now.
This generally occurs when there is a mismatch in the routes specified, or a component which is not present in our routing configuration, or if there is the use of multiple routes in our angular application which is not properly configured.
To access the route parameters, we use route.snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.
In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method.
For your routes to work, you need to update your template to dynamically load a component based on the URL path. To implement this functionality, you add the router-outlet directive to your template file.
scrollPositionRestoration wasn't working for me either. I solved it by not using the "mat-drawer" component from Angular Material with "scrollPositionRestoration: 'enabled'". The scroll position of "mat-drawer-content" cannot be restored to it's previous scroll state unfortunately. If you aren't using Angular Material, it may be the fault of another component.
If you want to scroll to the top with "mat-drawer" then use this:
// Navigate to the given route
public navigate (route: string): void {
this.router.navigateByUrl(route)
document.getElementsByTagName('mat-drawer-content')[0].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