1

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

Mr. Stash
  • 2,940
  • 3
  • 10
  • 24

1 Answers1

0

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.

Fabian Strathaus
  • 3,192
  • 1
  • 4
  • 26
  • 1
    Hi sir, thank you so much for your answer, it is working now. Was previously stuck as I thought .filterPredicate was used to replace .filter , turns out that I needed both lines. Thank you very much! – GeetaAmbrage Nov 02 '22 at 11:45
  • @ FabianStrathaus @ Fabian Strathaus Hi sir, do you know how I can edit the above code to return only certain addresses? For example, now when I enter filter value "Texas" , it returns the entire userobject "Mason" , however I would like it to only return userobject "Mason" with its addresses array only containing one address "St South, Texas" , filtering off the address "St West, Kansas". Thank you! – GeetaAmbrage Nov 15 '22 at 08:49