本文介绍了使用一个管道角度 2 过滤多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试仅使用一个 Pipe
基于多列过滤 Array
数据.现在,它过滤第一列值.请检查我下面的代码并帮助我解决这个问题.
I am trying to filter Array
data based on multiple columns using only one Pipe
. Right now, It filters first column value. Please check my below code and help me to sort this out.
我的代码:
@Pipe({ name: "dataFilter", pure: false })
export class DataFilterPipe implements PipeTransform {
transform(value: Array<any>, filter: any[]) {
if (!filter) {
return value;
} else if (value) {
return value.filter(item => {
for (var i = 0; i < filter.length; i++) {
if (filter[i][1] == undefined) {
return true;
} else if ((typeof item[filter[i][0]] === 'string' || item[filter[i][0]] instanceof String) &&
(item[filter[i][0]].toLowerCase().indexOf(filter[i][1]) !== -1)) {
return true;
}
return false;
}
});
}
}
}
我正在传递类似 dataFilter 的数据:[['column1',value1],['column2',value2],['column3',value3]]
.
推荐答案
这里是使用作为多列过滤器传递的对象的解决方案.我发现它比传递二维数组更方便:
Here is a solution using the object passed as multiple columns filter. I found it more convenient then passing a 2D array:
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: Array<any>, filter: {[key: string]: any }): Array<any> {
return items.filter(item => {
const notMatchingField = Object.keys(filter)
.find(key => item[key] !== filter[key]);
return !notMatchingField; // true if matches all fields
});
}
}
具有多列的对象数组:
this.people = [
{name: 'John', age: 27, sex: 'male'},
{name: 'Lara', age: 21, sex: 'female'},
{name: 'Rick', age: 29, sex: 'male'},
{name: 'Eva', age: 27, sex: 'female'},
{name: 'Mike', age: 27, sex: 'male'}
];
还有一个过滤器:
this.peopleFilter = {age: 27, sex: 'male'};
像这样使用:
<div *ngFor="let person of people | filter: peopleFilter;"></div>
因此,有两个人符合我们的标准:John 和 Mike.
As a result, two people are matching our criteria: John and Mike.
这是工作 plunker:多列过滤器管道演示.
Here is the working plunker: Multiple columns filter pipe demo.
这篇关于使用一个管道角度 2 过滤多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!