Angular Virtual Scroll Jumps around

6.6k views Asked by At

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.

1

There are 1 answers

3
Mr.Manhattan On BEST ANSWER

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>