Sasikumar
Sasikumar

Reputation: 888

Angular 7 disable scroll to top on Sub Route Change

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.

Upvotes: 2

Views: 3595

Answers (1)

terahertz
terahertz

Reputation: 3491

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.

Upvotes: 6

Related Questions