Mat-select内的CDK虚拟滚动用于Mat-option

时间:2018-09-10 22:44:02

标签: angular angular-material2 angular-cdk

有没有人能够在mat-select内部使用虚拟滚动,如下所示?

<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%2Fselect-reset-example.html无效,滚动时会产生奇怪的空白。

2 个答案:

答案 0 :(得分:1)

虚拟滚动视口需要一个大小才能知道滚动容器必须有多大。可以通过指定[itemSize]的{​​{1}}属性及其高度来实现。

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

<option>

答案 1 :(得分:0)

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

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

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

  openChange($event: boolean) {
    console.log("open change", $event);
    if ($event) {
      this.cdkVirtualScrollViewPort.scrollToIndex(0);
      this.cdkVirtualScrollViewPort.checkViewportSize();
    } else {
    }
  }

使用@ViewChild

获取对虚拟滚动视口的引用
@ViewChild(CdkVirtualScrollViewport, { static: false })
  cdkVirtualScrollViewPort: CdkVirtualScrollViewport;

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

<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>