Angular Material 2 DataSource filter with nested object

I have angular 4 project with material 2, I want to filter the data in MatTable. DataSource filter is working fine when we filter data on field which are not nested.

this.dataSource = new MatTableDataSource([
     { orderNumber: 1, orderInfo: { type: 'ABC'}, date: '12/3/2012 9:42:39 AM'},
     { orderNumber: 3, orderInfo: { type: 'Hello' }, date: '12/2/2018 9:42:39 AM'},
]);

Filter is working fine for orderNumber, date but not working properly with type field in orderInfo object.

1 answer

  • answered 2018-04-14 15:53 Sagar Kharche

    DataSource has filterPredicate method that need to override in our application as follows. Add this code in your component after data source initialization.

    this.dataSource.filterPredicate = (data, filter: string)  => {
      const accumulator = (currentTerm, key) => {
        return key === 'orderInfo' ? currentTerm + data.orderInfo.type : currentTerm + data[key];
      };
      const dataStr = Object.keys(data).reduce(accumulator, '').toLowerCase();
      // Transform the filter by converting it to lowercase and removing whitespace.
      const transformedFilter = filter.trim().toLowerCase();
      return dataStr.indexOf(transformedFilter) !== -1;
    };