Scroll Position Restoration in Angular

Sarun Intaralawan
2 min readJun 19, 2018

--

Applicable to Angular v6.1 and above

Version 6.1 of Angular i̶s̶ ̶j̶u̶s̶t̶ ̶a̶r̶o̶u̶n̶d̶ ̶t̶h̶e̶ ̶c̶o̶r̶n̶e̶r̶.̶ has been released. I̶t̶’̶s̶ ̶t̶i̶m̶e̶ ̶t̶o̶ ̶t̶a̶k̶e̶ ̶a̶ ̶s̶n̶e̶a̶k̶ ̶p̶e̶e̶k̶ ̶o̶f̶ ̶t̶h̶e̶ ̶c̶o̶o̶l̶ ̶t̶h̶i̶n̶g̶s̶ ̶t̶h̶a̶t̶ ̶i̶s̶ ̶c̶o̶m̶i̶n̶g̶!̶ It’s time to take a look at its new features!

One of the new feature is “Scroll Position Restoration”.

The Not-So-Good Old Days

Check out this example:

Note: When trying to go back, don’t use the back button on StackBlitz’s built-in browser, it will re-bundle the app. Instead, use the back key combination (Alt + Left Arrow). Eric Simons, could you fix this? lol

As you can see, when you navigate back from comp2, we scroll back to the top of comp1. This behaviour is mostly not preferred by most users.

How To Scroll Back To The Original Position?

Fortunately, in version 6.1 of Angular, there is a new option when initialising the RouterModule called scrollPositionRestore. Take a look at this example:

You can see that when navigating back, the page stays at the same position before you left.

Wait, There’s More!

There’s even more than this one option for this feature. Now there’s a service called ViewportScroller, which has the following methods:

  • setOffset
  • getScrollPosition
  • scrollToPosition
  • scrollToAnchor
  • setHistoryScrollRestoration

You can find more information about this feature at this pull request by Victor Savkin. (Yes, this PR dates back from October 2017, before Angular v6 was released!)

--

--

Sarun Intaralawan

Medical Student at Faculty of Medicine, Chulalongkorn University; Angular Contributor