2

I am using Angular Material Virtual scroll, the items get loaded correctly into the DOM, but while scrolling it happens that it jumps around and automatically jumps to the end.

<cdk-virtual-scroll-viewport #scrollViewport  (scrolledIndexChange)="scrolled($event)" [itemSize]="ITEM_SIZE"  class="my-virtual" >
    <div *cdkVirtualFor="let elem of elemtArray;" class="input-field-container ">

        <div class="my-style" >{{elem}} </div>

    </div>
</cdk-virtual-scroll-viewport>

The output of the method scrolled is the following, if the glitch occurs:

Scrolled:  105
Scrolled:  115
Scrolled:  106
Scrolled:  117
Scrolled:  109
Scrolled:  119
Scrolled:  110
Scrolled:  121

If this happens, it automatically scrolls to the end of the virtual scroll.

Roy
  • 7,811
  • 4
  • 24
  • 47
Elrond
  • 479
  • 1
  • 8
  • 21
  • In my case, Scroll was rendering new items, then suddenly removing them, and scrolling back to the top of the list. I couldn't find the reason, but adding a `trackByFn` to `cdkVirtualFor` fixed the issue for me. – Ashish Duklan Jul 25 '23 at 15:25

1 Answers1

4

Virtual scroll relies on an calculatable element height to calculate the offsets. To control this, set the input itemSize of cdk-virtual-scroll-viewport to whatever height you expect your items to have (in px).

if your ITEM_SIZE does not match the actual item size, then your described behavior will happen.

example:

css:

.my-style {
    height: 42px;
}

html:

<cdk-virtual-scroll-viewport [itemSize]="42" [...]>
     <!-- ... --->
</cdk-virtual-scroll-viewport>
Mr.Manhattan
  • 5,315
  • 3
  • 22
  • 34