Angular 6.1.0 - Restore scroll position not working as expected

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

This new feature in 6.1.0 doesn't work as expected. It seems that the ViewportScroller service tries to restore the scroll position before the DOM elements are populated so the max scroll height is essentially the device height. As a result, the scroll position restored is not doing the intended purpose.

I tried doing the following for custom scroll position restoration as suggested by the documentation but to no avail:

dataObsevable.pipe(withLatestFrom(scrollEvents)).subscribe(([list, e]) => {
  this.data = list;
  if (e.position) {
    viewPort.scrollToPosition(e.position);
  } else {
    viewPort.scrollToPosition([0, 0]);
  }
});

The position returned by the piped observable is correctly the value of the scroll position before the page was navigated from. However, it seems viewPort.scrollToPosition() tries to scroll the page before the DOM elements are done initialising so it's doing nothing.


Solution 1:

Scroll position restoration

There are two steps involved here,

  1. Store the scroll position of the div. while navigating to the other page.
  2. Assign the stored values to the div again when you come back to the page.

if RouterModule.forRoot(routes, { scrollPositionRestoration: 'enabled' }) does not work, try the following code:

HTML:

Add the following events in the div for which you want to restore scroll position

(scroll)="onScroll($event)" [scrollTop]="spt" [scrollLeft]="spl"

COMPONENT:

public spt:any;
public spl:any;

onScroll(event: any) {

sessionStorage.setItem('scroll',JSON.stringify({st:event.srcElement.scrollTop,sl:event.srcElement.scrollLeft}));
    
}

  ngOnInit() {

    if(sessionStorage.getItem('scroll'))
    {    
      //console.log("scrollTop available")
      var sp=JSON.parse(sessionStorage.getItem('scroll'));
      this.spt=sp.st;
      this.spl=sp.sl;
    }

}