具有多个条件的Angular 4数据过滤器

时间:2019-11-11 00:40:47

标签: angular angular-filters

我想根据多个下拉列表(4个下拉列表)选择过滤数据。

我可以选择任何一个下拉菜单或2个下拉菜单或多个下拉菜单。如何根据选择添加条件

spec.serviceAccountName

1 个答案:

答案 0 :(得分:1)

let selectedFilter1 = ['val1a', 'val1b', 'va1e'];
...
let selectedFilter4 = ['val4a', 'val4c'];

this.gridData = this.dataProvider.filter(data => {
        return (selectedFilter1.findIndex(filterVal => filterVal === data.column1) !== -1 || selectedFilter1.length === 0)
            && selectedFilter2.findIndex(filterVal => filterVal === data.column2) !== -1 || selectedFilter2.length === 0)
            && selectedFilter3.findIndex(filterVal => filterVal === data.column3) !== -1 || selectedFilter3.length === 0)
            && selectedFilter4.findIndex(filterVal => filterVal === data.column4) !== -1 || selectedFilter4.length === 0)
    });

或者如果您知道列的类型并且不想重复自己:

isInSelected<T>(columnVal: T, filter: T[]): boolean {
    return filter.length === 0
        || filter.findIndex(filterVal => filterVal === columnVal) !== -1
}

并像这样使用它:

this.gridData = this.dataProvider.filter(data => {
        return this.isInSelected<string>(data.column1, this.selectedFilter1)
            && this.isInSelected<number>(data.column2, this.selectedFilter2)
            && this.isInSelected<number>(data.column3, this.selectedFilter3)
            && this.isInSelected<string>(data.column4, this.selectedFilter4);
    });