【问题标题】:How to add filter for each column in MatTableModule in Angular?如何在 Angular 的 MatTableModule 中为每一列添加过滤器?
【发布时间】:2021-02-06 03:14:18
【问题描述】:

所有关于使用 MatTableModule 进行过滤的文章都建议添加一个 MatInputModule,用户可以在其中输入搜索/过滤文本:

<mat-form-field>
<mat-label>Filter Product</mat-label>
<input matInput type="text" [(ngModel)]="filterValue"
(blur)="filterProduct(filterValue)" placeholder="Search product name">
</mat-form-field>

当用户输入搜索/过滤文本时,上面的代码sn-p会调用函数filterProduct(...)

这就是filterProduct(...) 函数的样子:

public filterProduct = (value: string) => {
this.dataSource.filter = value;
}

这是处理过滤的常用代码 - this.dataSource.filter = value;

所以这表明过滤器应用于all 中的字段 dataSource MatTableModule 数据。

有没有办法为 MatTableModule 数据中的每个字段添加单独的过滤器?

【问题讨论】:

    标签: angular datatable


    【解决方案1】:

    尝试使用

    如果您的表格项目和成本有两个列,请为过滤器输入创建一个表单并将值传递给过滤器函数,如下所示:

    this.dataSource.filterPredicate = ((data, filter) => {
      const a = !filter.item || data.item.toLowerCase().includes(filter.item);
      const b = !filter.cost || +data.cost === +filter.cost;
      return a && b;
    }) as (Transaction, string) => boolean;
    
    this.form.valueChanges.subscribe(value => {
      const filter = {
        ...value,
        item: value.item.trim().toLowerCase()
      } as string;
      this.dataSource.filter = filter;
    });
    

    过滤多行:

    这里是多过滤器的 stackblitz 演示:https://stackblitz.com/edit/angular-uf1sdt-qbb81q?file=src/app/table-multiple-header-footer-example.html

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 2021-05-07
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多