Cdk virtual-scroll inside mat-select for mat-option

bhantol picture bhantol · Sep 11, 2018 · Viewed 9.3k times · Source

Has anyone been able to use virtual-scroll inside mat-select as shown below ?

<mat-form-field>
    <mat-select placeholder="State">
        <cdk-virtual-scroll-viewport autosize>
            <mat-option *cdkVirtualFor="let state of states" [value]="state">{{state}}</mat-option>
        </cdk-virtual-scroll-viewport>
    </mat-select>
</mat-form-field>

As you can see https://stackblitz.com/edit/angular-h4xptu?file=app%2Fselect-reset-example.html it does not work - causes weird blank space as you scroll.

Answer

kevobt picture kevobt · Dec 5, 2018

The virtual scroll viewport needs a size in order to know, how big the scroll container must be. This can be done by specifying the [itemSize] property of <cdk-virtual-scroll-viewport> and its height.

In your example the height of one <option> item is 48px. If you want to show five items at once, the container size would be 5 * 48 = 240:

<mat-form-field>
    <mat-select placeholder="State">
        <cdk-virtual-scroll-viewport [itemSize]="48" [style.height.px]=5*48>
            <mat-option *cdkVirtualFor="let state of states" [value]="state"> 
                {{state}}
            </mat-option>
        </cdk-virtual-scroll-viewport>
    </mat-select>
</mat-form-field>