Typescript 如何使用array.filter更新客户端angular5数组?
我正在Angular5中实现数组过滤 这是我的组件Typescript 如何使用array.filter更新客户端angular5数组?,typescript,angular5,array-filter,Typescript,Angular5,Array Filter,我正在Angular5中实现数组过滤 这是我的组件 ngOnInit() { this.getFileDetails(); this.recordsCopy = this.records; } getFileDetails() { this.appService.fetchFileDetails(this.filename).then((resp: any) => { if (resp.success) { this.records = resp.data; t
ngOnInit() {
this.getFileDetails();
this.recordsCopy = this.records;
}
getFileDetails() {
this.appService.fetchFileDetails(this.filename).then((resp: any) => {
if (resp.success) {
this.records = resp.data;
this.records.map(item=>{
item.editable = false;
})
}
});
}
nameSearchFilter(event : any){
const val = event.target.value.toLowerCase();
console.log(val);
this.recordsCopy = this.records.filter(function (d) {
return d.Name.toLowerCase().indexOf(val) !== -1 || !val;
});
}
这是我的component.html
<div class="tale-responsive">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Speciality</th>
<th>Credentials</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control" (keyup)='nameSearchFilter($event)'/>
</td>
<td>
<input type="text" class="form-control"/>
</td>
<td>
<input type="text" class="form-control" />
</td>
<td>
<input type="text" class="form-control"/>
</td>
</tr>
</tbody>
</table>
</div>
<div class="table-responsive">
<div class="table">
<tr>
<th>Name</th>
<th>Speciality</th>
<th>Credentials</th>
<th>City</th>
</tr>
<tr *ngFor="let record of records">
<td>{{record.Name}}</td>
<td>{{record.Specailty}}</td>
<td>{{record.Credentials}}</td>
<td>{{record.City}}</td>
</tr>
</div>
名称
特长
资格证书
城市
名称
特长
资格证书
城市
{{record.Name}
{{record.Specailty}}
{{record.Credentials}}
{{record.City}
我在keyup
angular事件上实现数组过滤,这样当用户启动type时,数组应该实时显示表过滤。
但它不起作用。我在代码中犯了什么错误?您正在修改
名称搜索过滤器
方法中的源记录
数组。那是错误的。您需要创建一个记录stodisplay
数组,并使用它来绘制表行,并将筛选结果分配到其中。您正在永久修改数据源
最简单的非角度方法是创建一个只分配的filteredRecords
副本,同时仍然过滤原始记录
this.filteredRecords = this.records.filter(...)
如果你想变得更有棱角,你可以制作一个过滤管,在你去模板的路上为你做这个。那么我应该在哪里修改代码,做什么呢?但是我的所有数组数据最初都在记录中,我在html中绑定了数组,所以在页面加载时,如果我将记录
替换为filteredRecords
因此页面加载时将不会有记录我也尝试过这个nameSearchFilter(事件:any){this.recordsCopy=this.records;const val=event.target.value.toLowerCase();console.log(val);this.recordsCopy=this.recordsCopy.filter(函数(d){返回d.Name.toLowerCase().indexOf(val)!==-1 | | |!val;});this.records=this.recordsCopy;}
但不在Anx中工作。我明白了。我刚刚发布了一个带有记录的静态声明数组的问题,来纠正我的过滤逻辑。我将您的逻辑应用到stackblitz代码中,该代码具有带记录的静态数组,因此可以正常工作。但当我在实际项目中使用您的逻辑时,它在AngularngOnInit上获取记录,因此停止工作。我已经更新了帖子。请相应地回复我也尝试过这个nameSearchFilter(event:any){this.recordsCopy=this.records;const val=event.target.value.toLowerCase();console.log(val);this.recordsCopy=this.recordsCopy.filter(函数(d){return d.Name.toLowerCase().indexOf(val)!=-1 | | | val;});this.records=this.recordsCopy;}
但不工作