Sitelet https://github.com/rx-angular/rx-angular/issues/1857
Skip to content

Virtual Scroll: scroll position jumps when using keepScrolledIndexOnPrepend #1857

Description

@m-gericke

Description

Image

This happens when inserting items during (viewRange) events while scrolling upwards. The scroll position jumps to the start of the previous item and scrolls upwards from there. This example is using the FixedSizeVirtualScrollStrategy but the bug should be present in all strategies.

This happens because the view index has already (correctly) changed when the keepScrolledIndexOnPrepend handler happens. That handler then jumps to the top of that index instead of the current offset of that index.

Steps to Reproduce the Issue

  1. add virtual scroll viewport with FixedSizeVirtualScrollStrategy
  2. enable [keepScrolledIndexOnPrepend] input
  3. add (viewRange) event handler that prepends items to the array

This is more noticable the larger the item height is.

Environment

Angular CLI: 19.1.3
Node: 18.19.1
Package Manager: pnpm 10.2.0
OS: win32 x64

Angular: 19.1.2
... animations, common, compiler, compiler-cli, core, forms
... platform-browser, platform-browser-dynamic, platform-server
... router

Package Version

@angular-devkit/architect 0.1901.3
@angular-devkit/build-angular 19.1.3
@angular-devkit/core 19.1.3
@angular-devkit/schematics 19.1.3
@angular/cli 19.1.3
@angular/ssr 19.1.3
@schematics/angular 19.1.3
rxjs 7.8.1
typescript 5.7.3

Notes

I've worked around this by including an offset between the current items top and the current scroll position like this:

// add offset parameter to scrollToIndex
scrollToIndex(index: number, behavior?: ScrollBehavior, offset: number = 0): void {
  const scrollTop = this.itemSize * index;
  this.viewport!.scrollTo(this.viewportOffset + scrollTop + offset, behavior);
}

// inside keepScrolledIndexOnPrepend handler
this.scrollToIndex(scrollTo, undefined,  this.scrollTop % this._itemSize);

This fix obviously only works for the FixedSizeVirtualScrollStrategy.

This also changes the public API of scrollToIndex, which might not be desirable. It is trivial to call viewport.scrollTo directly in during the keepScrolledIndexOnPrepend handling. I can provide a pull request for at least the FixedSizeVirtualScrollStrategy in either case if desired.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

</> Template@rx-angular/template related

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions