在 Angular 中,我根据在输入中输入的值进行过滤,但是当输入为空值时,我的数据不会返回。
我根据我在输入中输入的数据获取某些数据,但当输入为空时,并非所有数据都会返回。
applyFilter(value: string) {
const filterValue = value.trim().toLowerCase();
const filteredMap = new Map<string, any>();
this._todayShare.forEach((item, key) => {
if (key.toLowerCase().includes(filterValue) ||
JSON.stringify(item).toLowerCase().includes(filterValue)) {
filteredMap.set(key, item);
}
});
this._todayShare = filteredMap;
}
<input
[(ngModel)]="sharedsearchText"
(keyup)="applyFilter(sharedsearchText)"
style="width: 50%; margin-top: 1px; margin-bottom: 1px;"
matInput
placeholder="Ara..."
/>
您需要保留原始数据的副本,以便将来的过滤操作不会减少数据集。因为考虑一下
_todayShare
将包含 5 个值,然后您执行一个过滤器,用 2 个值覆盖 5 个值,因此丢失了 3 个值,因为我们没有保留原始值!
所以你需要备份
_todayShare
_todayShareBackup = structuredClone(_todayShare); // clone the data so that the updates on one does not affect the other
...
applyFilter(value: string) {
const filterValue = value.trim().toLowerCase();
const filteredMap = new Map<string, any>();
this._todayShareBackup.forEach((item, key) => {
if (key.toLowerCase().includes(filterValue) ||
JSON.stringify(item).toLowerCase().includes(filterValue)) {
filteredMap.set(key, item);
}
});
this._todayShare = filteredMap;
}
...