首页 > 解决方案 > Material DataTable 过滤控制

问题描述

我正在使用Angular Material Data Table并尝试对所有值进行过滤。我注意到的是,当使用 MatTableDataSource 时,过滤器仅搜索通过的实体的顶层,如果实体附加了相关记录,则不会搜索它。

是否可以控制过滤器搜索的深度并使其能够搜索附加的相关实体?

编辑 1 由原理图生成的示例代码:

@ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  @Input() dataSource: MatTableDataSource<TestEntity>;

  /** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
  displayedColumns = ['id', 'name', 'view_related_child'];

  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

编辑 2 个实体:

export class TestEntity {
    id: string;
    name: string;
    childEntity: ChildEntity;
}

export class ChildEntity {
    childId: string;
    childName: string;
    childDate: string;
}

标签: angularangular-material

解决方案


您可以将您的应用过滤器方法更改为:

applyFilter(filterValue: string) {
    console.log(filterValue)

    this.dataSource.filterPredicate = (data: TestEntity, filter: string) =>   data.childEntity.childName.indexOf(filter) != -1 
    filterValue = filterValue.trim(); 
    this.dataSource.filter = filterValue 
  }

根据 childEntity 的 childName 过滤数据, 工作演示


推荐阅读