Azim Sadikov
Azim Sadikov

Reputation: 182

How to come back to the same portion of data set in virtual scrolling?

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?

Upvotes: 2

Views: 2836

Answers (3)

greygreg87
greygreg87

Reputation: 152

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.

Upvotes: 0

Azim Sadikov
Azim Sadikov

Reputation: 182

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.

Upvotes: 2

Francesco Borzi
Francesco Borzi

Reputation: 61774

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.

Upvotes: 2

Related Questions