Angular 6 - Keep scroll position when the route changes

后端 未结 4 2061
萌比男神i
萌比男神i 2021-01-04 12:52

Previous Behavior:

Changing the route or navigation path would not affect the scroll position when navigating to another route. I.e the contents can

相关标签:
4条回答
  • 2021-01-04 13:06

    if scroll restoration doesnt work , Create a service that updates the current scroll Position on the change of that route and assign the scroll position to that service scroll position on ngOnit for the new route component and reset the service scroll.

    0 讨论(0)
  • 2021-01-04 13:16

    The scroll position won't change after the route is changed. This is always the default behaviour for Angular.

    However, lots of devs are manually doing a window.scroll(0, 0) to overwrite this behaviour.

    I would suggest you check if something in your code is doing this. Because it might be a newly installed 3rd party library or another developer's code commit.

    Also, according to the following official article:

    Angular v6.1 Now Available — TypeScript 2.9, Scroll Positioning, and more

    There is a new option to keep the original scroll position by using

    RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})

    I believe this is not directly related to the question you are asking but just something good to know.

    0 讨论(0)
  • 2021-01-04 13:19

    if it doesnt work with ScrollPositionRestoration:'enabled' configuration use the [scrollTop] property binding for the container and assign the value

    0 讨论(0)
  • 2021-01-04 13:28

    Seems like setting 'scrollPositionRestoration' to disabled fixes it

    RouterModule.forRoot(
      appRoutes,
      { scrollPositionRestoration: 'disabled' } // <-- HERE
    )
    

    See https://angular.io/api/router/ExtraOptions

    0 讨论(0)
提交回复
热议问题