首页 > 解决方案 > 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
      );
  }

标签: regexangularfilterangular-material

解决方案


使用数据源的属性 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"

推荐阅读