Angular scrollPositionRestoration without animation / smooth scrolling?

Viewed 1063

Using scrollPositionRestoration: 'enabled' for the RouterModule is really a nice feature but how to disable the scroll animation / smooth scrolling so it snaps to the position?

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      scrollPositionRestoration: 'enabled',
    }),
  ],
  exports: [RouterModule]
})
export class AppRoutingModule {
}

Background: Having smooth scrolling does not feel like navigating a "normal" website because normally if navigating back and forth there is no smooth scrolling.

3 Answers

The issue wasn't Angular, instead Bootstrap has set CSS smooth-scrolling to smooth.

Disabled it by $enable-smooth-scroll: false;

I was having the same problem. I tried using Mick's solution of changing the variable in bootstrap's "scss/_variables.scss" file but it didn't work out for me (Plus since it was in the node_modules which we don't share while the code is committed, any changes there wouldn't do any good as well, I guess). So I tried over riding in styles.css as:-

html {

scroll-behavior: auto !important

}

And it worked for me. I was having multiple CSS files in the global context for the project and maybe that's why the bootstrap variable change didn't work for me because other files may have interfered as well.

There is an open issue at Angular's github about scrollPositionRestoration

I tried to make an alternative, I hope it helps you:

https://stackblitz.com/edit/angular-ivy-jxm1mu?file=src%2Fapp%2Fapp.module.ts

I couldn't reproduce the navigate back behaviour with stackblitz because the app reloads.

When the user scrolls, save the scroll Y position and then, when the router emits the scrolling event, you make it not smooth.

window.scrollTo doc says that there is a value behavior: instant, I used auto because linter marked it as a error, so maybe it is not widely supported.

Related