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

问题描述 投票:0回答:1

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

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

this.gridData = this.dataProvider.filter(data => {
    return data.column1 == this.selectedFitler1
        && data.column2== this.selectedFitler2
        && data.column3 == this.selectedFitler3
        && data.column4 == this.selectedFitler4 })
angular angular-filters
1个回答
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);
    });
© www.soinside.com 2019 - 2024. All rights reserved.