1

I'm having a problem to get back to a particular scroll position. There is a list of lazy-loaded objects in my ObjectListComponent, once I click on the Object name I can check its details. There is a return button, which leads to a previous page with the list of Objects. The problem is that ObjectListComponent is being init from the start and I cannot get back to a previous state, the one before I checked a particular object's details. I need to have my scrollable list of objects and, if I enter ObjectComponent in order to check its details and want to go back to the list, I land on the ObjectList in the very same place my single object is, so I could scroll down and get more objects loaded.

There is an option like RouterModule.forRoot( appRoutes, { scrollPositionRestoration: 'disabled' } // <-- HERE )

But I have RouterModule.forChild and it doesn't accept extra options as an argument.

juliam
  • 79
  • 1
  • 2
  • 15
  • Idk if this would help, in my case it was also for child root - https://stackoverflow.com/questions/57214772/angular-8-restore-scroll-position-when-browser-back-button-is-selected-in-child – iBlehhz Sep 04 '19 at 08:54

1 Answers1

0

I had a chance to work on same requirement and there is no default configuration which would support scroll restoration in any front end frameworks. I have gone through many references with very complex code. I thought to develop by my own and implemented in following way:

  1. First get the scroll position using document.documentElement.scrollTop and map to this.router.url (previous url) in object.

  2. After returning to same page, compare with url in above object and apply corresponding position for that page.

  3. SPA Problem: Async loading of different pages takes different times to render hence apply scroll position effects. To solve this issue, we can use setInterval or setTimeout to properly apply scroll position.

  4. In your home component, subscribe to router events and start implementing

here:

scrollPos = {};
attempts = 5;
interval: any;
maxAttempts = 5;
scrollRestore() {
this.router.events.subscribe(event => {
if(event instanceof NavigationStart) {
this.scrollPos[this.router.url] = document.documentElement.scrollTop;
}
if(event instanceof NavigationEnd) {
this.scrollPos[event.url] ? 
this.applyScroll(this.scrollPos[event.url]):this.applyScroll(0)
}
});
}

applyScroll(pos) {
 this.interval = setInterval(() => {
  window.scrollTo(0, position);
  this.attempts++;
  this.clearScrollInterval(pos);
}, 30);
}

clearScrollInterval(pos) {
if (this.interval &&
  (this.attempts === this.maxAttempts || document.documentElement.scrollTop >= pos)) {
  clearInterval(this.interval);
  this.attempts= 0;
}
}
Vishwak
  • 103
  • 8