Angular Material多mat-autocomplete如何联动更新过滤后的选项列表
核心调整思路
你之前的问题根源是两个autocomplete的可选值都基于初始加载的全量数据唯一值列表,没有和表格实时过滤后的数据集绑定,所以不会随过滤结果联动。调整的核心逻辑是:
- 拿到表格每次过滤完成后的实时结果集,废弃固定的全量唯一值列表
- 把每个autocomplete的选项流和「输入框内容变化」「表格过滤结果变化」两个事件绑定,每次触发都重新计算当前可选的唯一值
具体实现步骤
首先你需要先持有实时的表格过滤后数据,以常用的MatTableDataSource为例:
// 新增声明:用于存储当前表格过滤后的完整数据 currentFilteredData$ = new BehaviorSubject<any[]>([]); // 初始化表格数据时,先给流赋初始全量值 this.yourDataService.getTableData().subscribe(tableData => { this.dataSource = new MatTableDataSource(tableData); this.currentFilteredData$.next(tableData); // 监听表格过滤事件,实时更新过滤后的数据 this.dataSource.filterChange.subscribe(() => { this.currentFilteredData$.next(this.dataSource.filteredData); }); });
然后修改你两个autocomplete的选项流逻辑,用combineLatest组合多个触发源:
// 替换原有的filteredCodes生成逻辑 this.filteredCodes = combineLatest([ this.filterCourseCodesControl.valueChanges.pipe(startWith('')), this.currentFilteredData$ ]).pipe( map(([inputValue, currentTableData]) => { // 先从当前过滤后的表格数据中提取courseCode的唯一值 const uniqueCurrentCodes = [...new Set(currentTableData.map(item => item.courseCode))]; // 再基于用户输入值做过滤 const filterVal = this._normalizeValue(inputValue); return uniqueCurrentCodes.filter(code => this._normalizeValue(code).includes(filterVal)); }) ); // 第二个autocomplete的filteredClaimedBy同理修改即可 this.filteredClaimedBy = combineLatest([ this.filterClaimedByControl.valueChanges.pipe(startWith('')), this.currentFilteredData$ ]).pipe( map(([inputValue, currentTableData]) => { const uniqueCurrentClaimedBy = [...new Set(currentTableData.map(item => item.claimedBy))]; const filterVal = this._normalizeValue(inputValue); return uniqueCurrentClaimedBy.filter(name => this._normalizeValue(name).includes(filterVal)); }) );
额外说明
你之前尝试的displayWith和这个需求无关,它的作用是控制autocomplete选中值后输入框内的显示格式,不需要用到。
现在不管哪个autocomplete先选值触发表格过滤,另一个autocomplete的选项都会自动基于最新的表格过滤结果重新生成唯一值列表,实现双向联动。
内容的提问来源于stack exchange,提问作者hego64
相关产品推荐
相关产品推荐

