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

Angular中清空筛选输入框后原始数据无法恢复的问题求助

问题解决:清空筛选框后原始数据无法恢复

问题根源在于你每次执行applyFilter时,都是基于当前已过滤的_todayShare创建临时备份,而非保存一份完整的原始全量数据副本。第一次筛选后,_todayShare已变为筛选结果,后续清空输入框时,备份的是已被过滤的数据,自然无法恢复全部原始内容。

修复方案:

  1. 新增变量存储原始全量数据
  2. 所有筛选操作基于原始数据执行,而非当前展示的已过滤数据

修改后的组件代码:

// 展示用的数据
_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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:50:08