[英]Cdk virtual-scroll inside mat-select for mat-option
有没有人能够在 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它不起作用 - 滚动时会导致奇怪的空白区域。
虚拟滚动视口需要一个大小才能知道滚动容器必须有多大。 这可以通过指定<cdk-virtual-scroll-viewport>
的[itemSize]
属性及其高度来完成。
在您的示例中,一个<option>
项目的高度为 48 像素。 如果您想一次显示五个项目,容器大小将为 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>
我想我已经解决了这个问题:
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
@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>
使用 *ngFor 添加额外的 mat-option,就好像您没有使用 cdk 虚拟滚动一样。 这不会向您的 select 列表添加任何其他选项,但确实允许默认选择值,同时还允许 cdk-virtual scroll 执行其操作。
<mat-select placeholder="State">
<cdk-virtual-scroll-viewport itemSize="10" [style.height.px]=10*100>
<mat-option *cdkVirtualFor="let state of states" [value]="state">{{state}}</mat-option>
</cdk-virtual-scroll-viewport>
<mat-option *ngFor="let state of states" [value]="state">
{{state}}</mat-option>
</mat-select>
@bhantol提到的步骤是正确的尝试执行此(您的解决方案) 链接步骤:1)打开下拉菜单2)一直向下滚动3)关闭下拉菜单4)打开下拉菜单...我看到一个很大的空白下拉列表。 你看到了什么?
有人为此解决了吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.