regex - Material Angular 添加正则表达式(regex)进行过滤
问题描述
我想在材料表数据过滤器上使用正则表达式。到目前为止,我已经为表格上的每一列使用了一个过滤器,但不知道如何使用正则表达式功能。我读过有关更改的内容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
);
}
解决方案
使用数据源的属性 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()
}
注意:我编辑了我的答案以制作更舒适的代码
注意 2:如果您想在代码中使用字符串变量进行定义,请小心使用 regExp。您需要考虑“\”必须写为“\\”,例如
let myExpresion="^\w" //BAD, myExpresion get the value "^w"
let myExpresion="^\\w" //GOOD, myExpresion get the value "^\w"
推荐阅读
- python - 将热图添加到 Folium 中的图层
- xml - 将 xml 反序列化为对象时,我保持为空
- java - 将(自动生成的?)EJB 代码从 Websphere 转换为 Glassfish
- c++ - Qt5 paintEvent() 区域太小
- ios - 部分用户购买In App Purchase时报错
- javascript - Javascript函数未成功调用
- sql - 如何在 Oracle 中不使用 TRUNC 获取天数
- tensorflow - 如何在 Keras 中定义 ConvLSTM 编码器解码器?
- r - purrr:加入嵌套在不同列表列中的小标题
- django - 用于前端的 Django Rest 框架视图和常规 django 视图