我目前正在开发一个组件,该组件使用 Material 2 表来显示一些数据。我需要能够编写自定义过滤器操作(例如价格 > 1)并组合多个过滤器。为了完成这项工作,我编写了一个自定义 filterPredicate:
customFilterPredicate(data: Coin, filters: Predicate[]): boolean {
var operators = {
'>=': function(a, b){
return +a >= +b
},
'<=': function(a, b){
return +a <= +b
}
}
if(filters.length == 0) return true;
let res = false;
for(var i = 0; i < filters.length; i++){
let conditionMet = operators[filters[i].op](data[filters[i].columnName], filters[i].val);
if(conditionMet) {
res = true;
} else {
res = false;
break;
}
}
return res
}
谓词类型的接口(interface):
export interface Predicate {
field: columnName
op: string;
val: number;
visible: boolean;
}
customFilterPredicate 遍历所有作为参数传递的过滤器,如果满足所有条件则返回 true,如果一个或多个条件不满足则返回 false。
现在我使用这个函数通过服务获取表的数据,设置我的数据源并替换数据源的filterPredicate:
setData(){
return new Promise((resolve, reject) => {
return this.coinService.getCoins()
.subscribe(coins => {
resolve(coins)
})
})
.then((data: Coin[]) => {
this.dataSource = new MatTableDataSource<Coin>(data);
this.dataSource.filterPredicate = this.customPredicate;
})
}
有趣的是,当我使用它时,过滤工作正常,但它总是抛出一个错误,说我不能用我的自定义过滤器替换 filterPredicate,因为它期望过滤器参数是一个字符串。
所以我的问题是,如何将 this.dataSource.filterPredicate 替换为我的,而不重写 material 2 包中的函数。有没有办法在 typescript 中做到这一点?
如果有人知道为什么这会起作用,尽管会抛出错误,那对哈哈来说会很有趣
最佳答案
目前不支持,但有一个开放的feature request在 Github 上。它已添加到功能列表中,因此可能值得关注。
在问题中,建议创建您自己的 DataSource
,并使用接受数组而不是字符串的过滤器。看看 MatTableDataSource它扩展了 DataSource类。
关于Angular 5 Material Table 用具有不同参数类型的函数替换 filterPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49887051/