Angular mat select配合ngx-mat-select-search过滤时选中chips消失如何解决
问题根因
你触发过滤时将未匹配搜索关键词的已选中选项从下拉选项数据源中移除了,mat-select 多选模式下会自动清除不在当前渲染选项列表内的选中值,因此绑定的选中值被更新导致 chips 消失,而你下方的已选列表直接读取了未被过滤影响的原始选中值数据源,所以不受影响。
修复方案
1. 调整过滤逻辑,始终保留已选中项在下拉数据源中
修改过滤函数,将已选中的选项强制合并到过滤后的列表中,避免被过滤逻辑移除:
// 原过滤逻辑示例 filterOptions() { const searchKey = this.searchControl.value?.toLowerCase() || ''; this.filteredOptions = this.allOptions.filter(item => item.label.toLowerCase().includes(searchKey) ); }
调整后:
// 调整后的过滤逻辑 filterOptions() { const searchKey = this.searchControl.value?.toLowerCase() || ''; // 匹配搜索词的选项 const matchedItems = this.allOptions.filter(item => item.label.toLowerCase().includes(searchKey) ); // 已选中的选项 const selectedItems = this.selectControl.value || []; // 合并两个列表并按唯一ID去重,避免重复展示 this.filteredOptions = Array.from( new Map([...matchedItems, ...selectedItems].map(item => [item.id, item])).values() ); // 可选:按原有排序规则重排,避免选中项位置突变影响交互体验 this.filteredOptions.sort((a, b) => a.label.localeCompare(b.label)); }
2. 补充正确的选项对比逻辑(可选,避免引用不一致导致的识别异常)
如果你的选项是对象类型,需要给 mat-select 绑定 compareWith 函数,按唯一标识而非对象引用判断是否选中:
<mat-select [formControl]="selectControl" [compareWith]="compareOption" multiple> <!-- ngx-mat-select-search 搜索框、mat-option 等内容 --> </mat-select>
compareOption(opt1: any, opt2: any): boolean { return opt1 && opt2 ? opt1.id === opt2.id : opt1 === opt2; }
3. 隐藏不匹配搜索词的已选中项(可选,优化交互)
如果不希望已选中但不匹配搜索词的选项出现在下拉列表里,可以给对应的 mat-option 加隐藏样式,不要直接从数据源中移除:
<mat-option *ngFor="let option of filteredOptions" [value]="option" [style.display]="isOptionVisible(option) ? 'block' : 'none'" > {{ option.label }} </mat-option>
isOptionVisible(option: any): boolean { const searchKey = this.searchControl.value?.toLowerCase() || ''; // 已选中但不匹配搜索词的项隐藏 return option.label.toLowerCase().includes(searchKey) || !this.selectControl.value?.includes(option); }
内容的提问来源于stack exchange,提问作者Vikram Sapate
相关产品推荐
相关产品推荐

