You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular15中cdk虚拟滚动+搜索的mat-select选中值不显示问题

Angular 15 mat-select搜索后选中值不显示问题解决

这个问题的核心原因是cdk-virtual-scroll-viewport的itemSize设置过小,导致虚拟滚动未正确渲染选中的选项元素,mat-select无法找到对应的mat-option来更新显示状态。

修复步骤:

  1. 修正虚拟滚动的itemSize值
    mat-option默认高度约为48px,将itemSize从5改为匹配选项实际高度的数值(比如48):
    <cdk-virtual-scroll-viewport [itemSize]="48" [style.height.px]="viewPortHeightPx" class="custom-viewport">
    
  2. 调整视口高度(可选)
    根据itemSize调整viewPortHeightPx的值,确保能显示足够数量的选项(例如设为240,对应5个默认高度的选项:48*5=240)。

额外优化建议:

  • 避免同时使用[(ngModel)]和[formControl],两种绑定方式会产生冲突,建议只保留[formControl],通过表单控件管理选中值。
  • 确认filteredItems的异步管道逻辑正确,搜索后返回的结果无过滤错误。

修改后的关键代码片段:

<mat-form-field>
<mat-select [formControl]="formControl"
            [placeholder]="placeholder"
            [matTooltip]="getTooltip(values)"
            [multiple]="multiple"
            [required]="required"
            (openedChange)="openChange($event)">

    <mat-option *ngIf="!hideSearch">
        <ngx-mat-select-search
            [placeholderLabel]="filterItem"
            [noEntriesFoundLabel]="noItemMatch"
            [formControl]="filterItemCtrl"
            [showToggleAllCheckbox]="showAllCheckbox"
            [toggleAllCheckboxChecked]="showAllCheckbox && multiple && items.length && values.length === items.length"
            (toggleAll)="checkAllItems($event)">
        </ngx-mat-select-search>
    </mat-option>

    <mat-option *ngIf="emptyItem">{{ emptyItem }}</mat-option>

    <cdk-virtual-scroll-viewport [itemSize]="48" [style.height.px]="240" class="custom-viewport">
        <mat-option *cdkVirtualFor="let item of filteredItems | async;" 
                    [value]="item"
                    (onSelectionChange)="clickOption($event)">
            <div>
                {{ item }}
            </div>
         </mat-option>
    </cdk-virtual-scroll-viewport>
</mat-select>
</mat-form-field>

itemSize设置正确后,虚拟滚动会正常渲染所需的选项元素,mat-select就能找到选中值对应的mat-option,从而正常显示选中内容。

内容的提问来源于stack exchange,提问作者help me code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:05:02