Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 - Keep scroll position when the route changes

Previous Behavior:

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

Current Behavior:

Changing the route will put you right back to the top of the page.

Action Done So Far:

Tested on current and a fresh new Angular 6 project

Is this a bug? change in feature? or is there a parameter I am missing.

like image 921
chickenninja565 Avatar asked Aug 16 '18 16:08

chickenninja565


People also ask

How do you keep the scroll position?

Preserve scroll position allows you to maintain the same scroll location when you transition between two screens. This applies to scroll depth in a vertical scroll, as well as the user's location inside a horizontal scrolling element. Figma automatically preserves your scroll position for Smart Animate.

How can I retain the scroll position of a scrollable area when pressing back button?

store the position in cookies and after that use the cookie to scroll the page to exact position .

What is scrollTop in angular?

ng-scrolltop demo: angular component that monitors current Y position in a long page or element then if scrolled down enough, shows up a clickable, unobtrusive icon that scrolls to top smoothly.


1 Answers

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.

like image 142
Xinan Avatar answered Oct 06 '22 22:10

Xinan