Search code examples
angularangular-materialangular-material-table

Angular MatTableDataSource filterPredicate : Filter sub-layers


I am using Angular's MatTableDataSource filterPredicate function

applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
}

or for custom filter function

this.dataSource.filterPredicate = function (record,filter) {
    // Custom filter logic
}

You may refer to this link https://material.angular.io/components/table/examples to see how the filter is supposed to work

I am trying to let the filter work till the sub-layer For example, my data is

const USERS: User[] = [
  {
    name: "Mason",
    addresses: [
      {
        street: "St West",
        city: "Kansas"
      },
      {
        street: "St South",
        city: "Texas"
      }
    ]
  },
  {
    name: "Jason",
    addresses: [
      {
        street: "St West",
        city: "Utah"
      },
      {
        street: "St North",
        city: "Ohio"
      }
    ]
  }
];

I would like to make it such that when I enter filterValue "St West", both users Mason and Jason will appear Currently, the filter is only able to work till the first/User layer, it does not look into the data in the second/Address layer

Does anyone know how to do this?

Thank you


Solution

  • You should provide a custom filter predicate, which is highly depending on your needs regarding which fields the filter should apply on. If you just want to check whether your filter criteria matches any address object containing the exact street, you can use the following filter:

    this.dataSource.filterPredicate = function (record,filter) {
        return record.addresses.some(address => address.street === filter);
    }
    

    Of course you can enhance this function to check for other fields as well.