关于angular:垫选择中的cdk虚拟滚动

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

任何人都可以在mat-select内部使用虚拟滚动,如下所示吗?

1
2
3
4
5
6
7
<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>

如您所见https://stackblitz.com/edit/angular-h4xptu?file=app/select-reset-example.html它不起作用-滚动时会产生奇怪的空格。


虚拟滚动视口需要一个大小才能知道滚动容器必须有多大。这可以通过指定<cdk-virtual-scroll-viewport>[itemSize]属性及其高度来实现。

在您的示例中,一个<option>项目的高度为48px。如果要一次显示五个项目,则容器大小将为5 * 48 = 240:

1
2
3
4
5
6
7
8
9
<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>


我想我已经解决了这个问题:

https://stackblitz.com/edit/angular-gs4scp

关键是当垫选择打开面板时,我们触发cdkVirtualScrollViewPort滚动并检查视图端口大小。

1
2
3
4
5
6
7
8
  openChange($event: boolean) {
    console.log("open change", $event);
    if ($event) {
      this.cdkVirtualScrollViewPort.scrollToIndex(0);
      this.cdkVirtualScrollViewPort.checkViewportSize();
    } else {
    }
  }

使用@ViewChild

在此处获得对虚拟滚动视口的引用

1
2
@ViewChild(CdkVirtualScrollViewport, { static: false })
  cdkVirtualScrollViewPort: CdkVirtualScrollViewport;

模板中的其他相关部分非常简单:-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<mat-form-field>
    <mat-select [formControl]="itemSelect"
  placeholder="Select Item"
  (openedChange)="openChange($event)">
    <mat-select-trigger>
      {{ itemTrigger }}
    </mat-select-trigger>
        <cdk-virtual-scroll-viewport itemSize="5" minBufferPx="200" maxBufferPx="400" class="example-viewport-select">
            <mat-option *cdkVirtualFor="let item of items" [value]="item"
                (onSelectionChange)="onSelectionChange($event)">{{item}}</mat-option>
        </cdk-virtual-scroll-viewport>
    </mat-select>
    <mat-hint>Justa hint</mat-hint>
</mat-form-field>