在这里,我有folderObjs
数组,并且该数组的Console在下面的代码中,我输入了搜索输入字段,我想按可能的方式通过folderName和folderSize对该数组进行搜索?
HTML
<mat-form-field>
<input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search">
</mat-form-field>
<div *ngFor="let folder of folderObjs">
<span>{{folder.folderName}}</span>
<span>{{folder.folderSize}}</span>
</div>
TS
folderObjs : Folder[] = [];
applyFilter(filterValue) {
console.log(this.folderObjs);
// 0: {folderid: 781, folderName: "pelu folder",folderActivity: "true", …}
1: {folderid: 782, folderName: "biju folder", folderActivity: "true", …}
filter: "d"
length: 2
this.folderObjs.filter = filterValue.trim().toLowerCase();
}
答案 0 :(得分:1)
const folderObjs = [
{name: "Jane", lastName: "Doe"},
{name: "john", lastName: "Snow"},
{name: "Tyrion", lastName: "Lannister"},
{name: "Lorem", lastName: "Ipsum"},
]
applyFilter(filterValue) {
folderObjs.filter((val) => {
return val.name.toLowerCase().indexOf(filterValue) > -1;
});
}
以上代码将过滤基于数据的名称属性。
applyFilter(filterValue, filterBy) {
folderObjs.filter((val) => {
return val[filterBy].toLowerCase().indexOf(filterValue) > -1;
});
}
也可以通过filterBy Option,希望对您有所帮助
答案 1 :(得分:1)
这将起作用,首先将folderObjs的副本复制到folderObjCopy ,因为当搜索值为空时,我们必须重新填充所有值。
applyFilter(filterValue) {
let val = filterValue.toLowerCase();
let searchColumns = ['folderName','folderSize'];
if (val.length > 0) {
this.folderObjs = this.folderObjCopy.filter(function (d) {
let matchFound = false;
for (let data of search_columns) {
let value = "" + d[data];
if (value.toLowerCase().indexOf(val) !== -1 || !val) {
matchFound = true;
break;
}
}
return matchFound;
});
} else {
this.folderObjs = this.folderObjCopy;
}
}
注意:将会有更多优化的解决方案,这只是我的实现。请告诉我这是否无效
答案 2 :(得分:1)
创建自定义管道
filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(value: any, searchValue): any {
if (!searchValue) return value;
return value.filter((v) =>
v.name.toLowerCase().indexOf(searchValue.toLowerCase()) > -1 ||
v.size.toLowerCase().indexOf(searchValue.toLowerCase()) > -1)
}
}
component.ts
<input type="search" [(ngModel)]="search">
<div *ngFor="let f of (folderObjs | filter:search)as folder">
{{f.name}}
{{f.size}}
</div>
<div *ngIf="(folderObjs | filter:search).length <1">
Not Found
</div>
答案 3 :(得分:0)
理想情况下,您可以使用管道或filter()来实现这一目标。
sortedArray : Folder[] = [];
applyFilter(val: string) {
this.sortedArray = this.folderObjs.filter(x =>
x.folderName.toLowerCase().indexOf(val.trim().toLowerCase()) !== -1 ||
x.folderSize.toLowerCase().indexOf(val.trim().toLowerCase()) !== -1)
}