Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cdk-virtual-scroll with mat-autocomplete works irregular

I try to use the cdk-virtual-scroll inside a mat-autocomplete:

<mat-form-field>
  <input type="text" placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl2"
     [matAutocomplete]="auto">
  <mat-autocomplete #auto="matAutocomplete">
    <cdk-virtual-scroll-viewport class="autocomplete-test-viewport" itemSize="50" minBufferPx="500" maxBufferPx="750">
      <mat-option *cdkVirtualFor="let option of options" [value]="option" class="autocomplete-item">
      {{option}}
      </mat-option>
    </cdk-virtual-scroll-viewport>
  </mat-autocomplete>

However the virtual scroll works irregularly in this setup. I generate 200 options but if i scroll slowly by using the scrollbar down arrow (chrome) it stalls around 14. Similar setup with a mat-select doesn't have this problem.

See https://stackblitz.com/edit/angular-xv1n2e?file=src/app/app.component.html for the whole example setup (mat-autocomplete and mat-select with the cdk-virtual-scroll).

Has anyone a working mat-autocomplete with the cdk-virtual-scroll?

like image 568
IHaanstra Avatar asked Oct 30 '18 22:10

IHaanstra


1 Answers

I check your code and made some tests to understant the strange behaviour. If you subscribe to the scrolledIndexChange output event on the CdkVirtualScrollViewport, and log the index in console, you can see that :

  • When you use the wheel, always an exact number of items are scrolled (2 for me) so the scroll index will change this way : 0 -> 2 -> 4 -> 6 ...
  • When you click on the down arrow of the scroll bar you can see
    that a scroll step don't match exactly to one item height. And the
    scroll change this way 1 -> 2 -> 3 -> 4 -> 5 -> 4 -> 5 -> 4 ... and
    loop between two values.

A solution should be to fix the scroll step (don't know how to do this yet) so if the user clicks on scrollbar (top or down), scroll exactly the height of one item.

Other solution, use the scrollToIndex method of the CdkVirtualScrollViewport to scroll to the next / previous index when user clicks on top / down arrow of scroll bar (but not when user use wheel to scroll)

like image 188
thib_o_o Avatar answered Nov 15 '22 23:11

thib_o_o