我有一个角度应用程序,用于显示名称列表。我有一个搜索输入可过滤该列表。
<input [ngModel]="searchStr" (ngModelChange)="modelChange($event)" type="text" id="employeeName">
该组件具有用于modelChange()的逻辑,以捕获输入字符串并通过该字符串过滤我的名字。这些数据最初来自ngInit()中的服务。我的问题是,每次在输入框中进行击键时,我都会使用过滤后的数组覆盖我的名称数组。当输入为空白时,如何编写此逻辑以将数组重置为其原始内容?
modelChange(str: string): void {
debugger;
this.searchStr = str;
this.employeeList = this.employeeList.filter(emp => emp.name.includes(this.searchStr));
}
HTML模板
<div *ngFor="let employee Of employeeList>
employee.name
</div>
您要覆盖modelChange中的同一数组,因此,如果要恢复到原始数组(在某种条件下),则必须在某个位置保留原始数组的引用,或者不要完全覆盖原始数组。维护另一个数组以用于显示,假设您将其命名为 displayArr
您的代码将像这样更新
public displayArr:any[] = []
modelChange(str: string): void {
debugger;
this.searchStr = str;
//if some search string is provided, then filter the original array
if(str)
{
this.displayArr = this.employeeList.filter(emp => emp.name.includes(this.searchStr));
}
else //if no search string is provided then don't filter the array and return it as it is.
{
this.displayArr = this.employeeList;
}
}
您应将数组保存在中间变量中,如下所示:
const filtered = [];
const unfiltered = [v1, v2, v3];
最初将值从unfiltered
复制到filtered
。过滤后,将unfiltered
个过滤后的值复制到filtered
,然后在需要时还原