Angular中清空筛选输入框后原始数据无法恢复的问题求助
问题解决:清空筛选框后原始数据无法恢复
问题根源在于你每次执行applyFilter时,都是基于当前已过滤的_todayShare创建临时备份,而非保存一份完整的原始全量数据副本。第一次筛选后,_todayShare已变为筛选结果,后续清空输入框时,备份的是已被过滤的数据,自然无法恢复全部原始内容。
修复方案:
- 新增变量存储原始全量数据
- 所有筛选操作基于原始数据执行,而非当前展示的已过滤数据
修改后的组件代码:
// 展示用的数据 _todayShare: Map<string, any> = new Map<string, any>(); // 新增:存储原始全量数据的备份 originalTodayShare: Map<string, any> = new Map<string, any>(); ngOnInit() { // 这里假设是获取全量数据的逻辑(比如接口请求、本地数据初始化) this._todayShare = new Map<string, any>(); // 把完整的原始数据存入备份变量 this.originalTodayShare = new Map<string, any>(this._todayShare); .... } applyFilter(value: string) { const filterValue = value.trim().toLowerCase(); const filteredMap = new Map<string, any>(); // 基于原始全量数据进行筛选 this.originalTodayShare.forEach((item, key) => { if (key.toLowerCase().includes(filterValue) || JSON.stringify(item).toLowerCase().includes(filterValue)) { filteredMap.set(key, item); } }); // 更新展示用的数据 this._todayShare = filteredMap; }
额外优化(可选):
当输入框为空时,直接恢复原始数据,避免不必要的遍历操作:
applyFilter(value: string) { const filterValue = value.trim().toLowerCase(); if (!filterValue) { // 清空输入框时直接恢复全部原始数据 this._todayShare = new Map<string, any>(this.originalTodayShare); return; } const filteredMap = new Map<string, any>(); this.originalTodayShare.forEach((item, key) => { if (key.toLowerCase().includes(filterValue) || JSON.stringify(item).toLowerCase().includes(filterValue)) { filteredMap.set(key, item); } }); this._todayShare = filteredMap; }
修改后,清空输入框即可重新展示全部原始数据。
内容的提问来源于stack exchange,提问作者Serkan
相关产品推荐
相关产品推荐

