2
votes

I have 2 options for scrolling to the top of the page. First,

router.events.subscribe((evt) => {
    if (evt instanceof NavigationEnd) {
        window.scroll({
            top: 0,
            left: 0,
            behavior: 'smooth'
        });
    }
});

and the second option is available from Angular 6 is,

RouterModule.forRoot(AppRoutes, { 
      scrollPositionRestoration: "enabled"
})

When I change my route, Page is moving to top which is working as expected. I have tab section at almost bottom of the page using sub route. When the sub route is triggered, the page is moving to the top of the page instead of remaining in the tab section.

So I need to disable the scroll to top functionality on the sub route. Is there any way to do it?

Any help/idea is appreciated.

1
Did you found an elegant solution to this because i am facing the same issue?AnHa
any solution to this?Ayyash
In some project, the scroll is given to a div and not to the main body. So, if u write a scroll to the body, it won`t work. Write to that particular div. Is that a help ?Sasikumar

1 Answers

3
votes

It might work if you check the current route is one of those sub routes of your tab section before you scroll to top.

//for scalability, define routes you don't want to scroll to top in a string array

const noScrollRoutes: string[] = ['route/tabSubRoute1', 'route/tabSubRoute2'];

router.events.subscribe((evt) => {
    if (evt instanceof NavigationEnd) {
        if(noScrollRoutes.find(this.router.url) == undefined){ //if can't a route in predefined array, scroll to top
           window.scroll({
               top: 0,
               left: 0,
               behavior: 'smooth'
           });
        }
    }
});

Also, you probably need to remove scrollPositionRestoration: "enabled", keep it disabled.