Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling to top in angular after route change and new component loads not working

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.

like image 408
Piyush dhore Avatar asked Apr 04 '19 09:04

Piyush dhore


People also ask

Can not match any routes Angular?

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.

How does Angular routing handle route parameters?

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.

How does Angular determine routing change?

In order to detect route change at any moment in AngularJS, this can be achieved by using the $on() method.

Which directive is used for loading component based on routes in Angular?

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.


1 Answers

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)
}
like image 99
Sert42 Avatar answered Sep 21 '22 12:09

Sert42