2

There is a wonderful pattern of optimizing rendering of large data sets called virtual scrolling. In this specific case I am using Angular Material CDK api's https://material.angular.io/cdk/scrolling/overview to get that behavior. However, I have a requirement when user navigates to different page and comes back, user should be at that specific location she left (ex. navigated to details of item 3498 and when comes back should start at item 3498 not item 1). What is the best way to achieve that?

Francesco Borzi
  • 37,945
  • 31
  • 126
  • 195
Azim Sadikov
  • 162
  • 9
  • How are you keeping track of where the user was? I.e. how does Angular remember you were at item 3498? If you don't have that anywhere you won't be able to scroll to it. – Berin Loritsch May 13 '19 at 17:26
  • I can assign uid to each item, and when user navigates back scroll to that element but virtual scrolling only renders items that fits in to viewport and item most likely will not be in the DOM so can not scroll to element that does not exist – Azim Sadikov May 13 '19 at 17:44

3 Answers3

2

You can inject the CdkVirtualScrollViewport view child:

@ViewChild(CdkVirtualScrollViewport) virtualScroll: CdkVirtualScrollViewport;

then you can play with methods like this.getOffsetToRenderedContentStart() and this.setRenderedContentOffset() to save and restore the original scroll location.

You can, for example, store this information inside a service or localstorage.

Francesco Borzi
  • 37,945
  • 31
  • 126
  • 195
1

Implemented what Francesco Borzi suggested and it works perfectly. here is the stackblitz implementation. Most of the action is happening in cdk-virtual-scroll-overview-example file.

Azim Sadikov
  • 162
  • 9
0

It's worth to mention that there is another useful pair of methods: measureScrollOffset and scrollToOffset. Method measureScrollOffset:

Gets the current scroll offset from the start of the viewport (in pixels).

So, it takes into account what user see, not rendered content - like getOffsetToRenderedContentStart - for this method I couldn't be able to retrieve relative small scroll values.

greygreg87
  • 96
  • 9