我想在物料表数据过滤器上使用正则表达式。到目前为止,我已经为表上的每一列使用了过滤器,但是对如何使用正则表达式功能一无所知。我已经读过有关更改customfilterpredicate
的信息,但似乎做不到。
我的过滤代码很长,但这是我的customfilterpredicate
的样子。我想使用正则表达式对其进行转换:
customFilterPredicate() {
const myFilterPredicate = (data: IApiDataFile, filter: string): boolean => {
const searchString = JSON.parse(filter);
const unitFound = data.unit.toString().trim().toLowerCase().indexOf(searchString.unit.toLowerCase()) !== -1;
const file_nameFound = data.file_name.toString().trim().toLowerCase().indexOf(searchString.file_name.toLowerCase()) !== -1;
if (searchString.topFilter) {
return unitFound || file_nameFound;
} else {
return unitFound && file_nameFound;
}
};
return myFilterPredicate;
}
filterSubscribe() {
this.unitFilter.valueChanges.subscribe(unitFilterValue => {
this.filteredValues.unit = unitFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
this.filteredValues.topFilter = false;
console.log('in filterSubscribe()');
});
this.file_nameFilter.valueChanges.subscribe(file_nameFilterValue => {
this.filteredValues.file_name = file_nameFilterValue;
this.dataSource.filter = JSON.stringify(this.filteredValues);
this.filteredValues.topFilter = false;
});
this.dataSource.filterPredicate = this.customFilterPredicate();
}
然后
public ngOnInit() {
interval(60 * 1000).pipe(
flatMap(() => this.ApiDataFileService.getApiDataFiles())).subscribe(
ApiDataFiles => {
this.filteredApiDataFiles = ApiDataFiles;
this.dataSource = new MatTableDataSource<IApiDataFile>(this.filteredApiDataFiles);
this.filterSubscribe();
this.dataSource.filter = JSON.stringify(this.filteredValues);
this.filteredValues.topFilter = false;
},
error => this.errorMessage = error as any
);
}
答案 0 :(得分:1)
使用数据源的属性filterPredicate。如果您的数据源是示例中的典型
dataSource = new MatTableDataSource(ELEMENT_DATA);
您可以定义在applyFilterFunction中更改的regExpr变量
regExpr:any; //<--define a variable
applyFilter(filterValue: string) {
this.regExpr = new RegExp(filterValue);
this.dataSource.filter = filterValue;
}
然后您可以创建类似的功能
regExprFilter()
{
return (data: any, filter: string) => {
try {
return this.regExpr.test(data.name)
} catch (e) {
return false
}
}
}
然后在ngOnInit中更改filterPredicate
ngOnInit() {
this.dataSource.filterPredicate =this.regExprFilter()
}
请参阅stackblitz
注意:我编辑了答案以编写更舒适的代码
注2:如果要在代码中使用字符串变量进行定义,请小心使用regExp。您需要记帐“ \”必须写为“ \\”,例如
let myExpresion="^\w" //BAD, myExpresion get the value "^w"
let myExpresion="^\\w" //GOOD, myExpresion get the value "^\w"