我有一个user[]
对象,该对象从API获取数据。我正在尝试根据fullName
(对象的属性)过滤数据,在keyup.enter
上它会调用filterUser()
函数。这是我编写过滤器逻辑的地方。数据正在获取过滤器,但Angular无法渲染它,我不知道我在做什么错。
我将过滤后的数据保存在filterData
类型的对象User[]
中。
User-list.html
<div *ngIf="users?.length > 0">
<div> <input type="text" (keyup.enter)="filterUser($event)"> </div> <!--function triggering here-->
<div *ngFor="let item of items">
{{item.attribute.fullName}}
</div>
</div>
User-list.component.ts
// assuming users has some data
items: User[]
filterData: User[];
filterUser( searchTerm: string) {
this.filterCount = 0;
console.log('searchTerm', searchTerm);
console.log(typeof(this.items));
if (!this.items || !searchTerm) {
return this.items;
}
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].attributes.fullName.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1) { this.filterData[i].attributes.fullName = this.items[i].attributes.fullName;
this.filterCount++;
}
}
this.items = this.filterData;// I'm not able to copy data back to this.items
}
我不知道我在想什么。我需要使用ngOnChanges()
吗?。
答案 0 :(得分:0)
将匹配项复制到FilteredData列表中时出错。这是使用传播运算符copy的可能解决方案:
class Test {
// assuming users has some data
constructor() {
this.items = [
{ attributes: { fullName: 'toto1' } },
{ attributes: { fullName: 'toto2' } },
{ attributes: { fullName: 'tutu3' } }
];
this.filterData = [];
}
filterUser(searchTerm) {
this.filterCount = 0;
console.log('searchTerm', searchTerm);
console.log(typeof (this.items));
if (!this.items || !searchTerm) {
return this.items;
}
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].attributes.fullName.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1) {
this.filterData[i] = { ...this.items[i] }; // Copy full object using spread operator
this.filterCount++;
}
}
this.items = this.filterData;// I'm not able to copy data back to this.items
}
}
let test = new Test();
test.filterUser('toto');
console.log(test.items);
答案 1 :(得分:0)
您可以通过创建自定义管道
进行过滤filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
searchText=searchText
if(!items){ return ;}
if(!searchText){
return items;
}
return items.filter( it => {
return it['fullName'].toLowerCase().includes(searchText);
});
}
}
在app.module.ts文件中注册管道
import {
FilterPipe
} from 'PipePath'; //give the path of custom created pipe
declarations: [...,FilterPipe],
user-list.html
<div *ngIf="users?.length > 0">
<div> <input type="text" (keyup.enter)="filterUser($event)" [(ngModel)]="search"> </div>
<div *ngFor="let item of items | filter : search">
{{item.attribute.fullName}}
</div>
</div>
在使用ngModel时,在ts文件中声明搜索变量。
user-list.ts
search;
这将解决您的问题。