Aeseir
Aeseir

Reputation: 8414

Material DataTable filtering control

I am using Angular Material Data Table and am trying to implement filtering accross all the values. What i am noticing is that when using MatTableDataSource, filter only searches the top level of entities that are passed, if the entity has a related record attached it won't search it.

Is it possible control how deep a filter search goes and enable it to search the attached related entities?

Edit 1 Example Code generated by schematics:

@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;
  }

Edit 2 Entities:

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

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

Upvotes: 0

Views: 394

Answers (1)

Lia
Lia

Reputation: 11982

you can change your apply filter method to this:

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 
  }

to filter the data based on childName of childEntity, working demo

Upvotes: 2

Related Questions