如何使用通配符过滤 MatTableDataSource

How do I filter MatTableDataSource using wildcards

我正在使用 Angular Material 网站 https://material.angular.io/components/table/examples

中的示例 Table with filtering

我想让用户使用通配符进行搜索。在这种情况下,%

我写了以下内容:

    const filterValue = (event.target as HTMLInputElement).value;

    let filterArray = filterValue.trim().toLowerCase().split("%");

    for (let fil of filterArray) {
      //I know this line below won't work, as it will just replace the filter with each iteration, but showing for sake of example
      this.tableData.filter = fil;
      
    }

因此,如果用户在输入字段中键入 one%two,我希望过滤器找到 table 行,其中“一”和“二”这两个词都存在于该行的某处。

我已经尝试了多种代码变体,但似乎没有一个是正确的。关于如何使这项工作有任何想法吗?

您必须像这样覆盖 this.dataSource.filterPredicate 的默认实现:

constructor() {
    this.dataSource.filterPredicate = ((data, filters) => {
      let match = false;
      const filtersList = JSON.parse(filters);

      filtersList.forEach(filterObj => {
        match =
          match || !filterObj ||
          Object.values(data)
            .map(t => t.toLocaleString().toLocaleLowerCase())
            .includes(filterObj);
      });
      return match;
    }) as (PeriodicElement, string) => boolean;
  } 

并且在您的 applyFilter 方法中,您需要通过 JSON.stringify(filterArray); 将数组传递给 filterPredicate,如下所示:

applyFilter(filterValue: KeyboardEvent) {
    let filterArray = (filterValue.target as any).value
      .trim()
      .toLowerCase()
      .split('%');
    this.dataSource.filter = JSON.stringify(filterArray);
  } 

Here 是我为您编写的完整示例。

我能够通过在我的 applyFilter() 方法中使用以下代码来完成此操作:

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;

    let filterArray = filterValue.trim().toLowerCase().split("%");

    let filteredData = [];

    //loop through each word provided in the filter and push matching arrays from the dataset to filterdData temporary holder
    for (let str of filterArray) {
      filteredData.push(
        this.data.filter((o) =>
          Object.keys(o).some((k) => String(o[k]).toLowerCase().includes(str))
        )
      );
    }

    //filter down final dataset with array items that occur in each array producded by each search term provided
    filteredData = filteredData.reduce((a, b) =>
      a.filter((c) => b.includes(c))
    );

    this.tableData.data = filteredData;
  }

我能够从每个问题中提取信息以形成满足我需求的解决方案: