我想我已经解决了这个问题:
https://stackblitz.com/edit/angular-gs4scp
关键是当 mat select 打开面板时,我们触发 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>