HannaAB
HannaAB

Reputation: 23

Angular Material autocomplete 's mat-option with two searchable value

I'm new to angular and I have a mat-autocomplete as search field and I want each of my mat-option to be searchable with 2 value for example with a name and with an id:

options = [{name: 'x', id: 123},{name: 'y', id:142}] 

any body know how I can do that?

Upvotes: 0

Views: 2127

Answers (1)

Fabian Küng
Fabian Küng

Reputation: 6183

If you have a look at the Angular Material Autocomplete examples, especially the one called Filter autocomplete you will see how the filtering is done and you can easily extend it to filter multiple values.

From the example (keep in mind here the options array is just an array of strings, so no properties are accessed/filtered):

private _filter(value: string): string[] {
  const filterValue = value.toLowerCase();
  return this.options.filter(option => option.toLowerCase().includes(filterValue));
}

We could rewrite this to the following to filter an additional id attribute (assuming options is an array of objects with the properties name and id):

private _filter(value: string): Option[] {
  const filterValue = value.toLowerCase();
  return this.options.filter(option => String(option.id).toLowerCase().indexOf(filterValue ) > -1 || 
  option.name.toLowerCase().indexOf(filterValue ) > -1);
}

Here is a stackblitz showing the filtering mentioned above.

Upvotes: 1

Related Questions