Reputation: 541
I have a little problem, I have this:
foo = {
parent1:[{
data: "John",
},
{
data: "Adam",
},
{
data: "Eva",
}],
parent2:[{
data: "Ricky",
}]
}
and my autocomplete:
<input type="text" matInput [formControl]="query" [matAutocomplete]="autoGroup"/>
<mat-autocomplete #autoGroup="matAutocomplete">
<mat-optgroup *ngFor="let parents of foo | keyvalue" [label]="parents.key">
<mat-option *ngFor="let data of parents.value" [value]="data.data">
{{ data.data }}
</mat-option>
</mat-optgroup>
</mat-autocomplete>
And I want to set it a filter - I just want to filter by "data", for ex. if i type "John" - it will only remain John with optgroup "parent1" I've created demo:
https://stackblitz.com/edit/angular-syzdzg-ytejbp?file=src%2Fapp%2Fautocomplete-filter-example.html
Thanks in advance!
Upvotes: 0
Views: 793
Reputation: 40592
I don't recommend you use KeyValuePipe pipe because it's impure, it means it would be called and translate you object to a new array every change detection cycle. See Pure and impure pipes section of the docs and this SO question.
In any case it's easier to transform the object into an array and filter it after. You can find the filter autocomplete example in the angular material docs. In your case it looks like:
...
@Component(...)
export class AutocompleteFilterExample {
...
readonly filteredFoo$ = this.query.valueChanges.pipe(
map((query = '') => {
const lowerCaseQuery = query.toLocaleLowerCase().trim();
return Object.entries(this.foo)
.map(([parentId, items]) => ([
parentId,
items.filter(item => {
const lowerCaseData = item.data.toLocaleLowerCase();
return lowerCaseData.includes(lowerCaseQuery);
})
]))
.filter(([prentId, items]) => items.length);
})
);
}
<input type="text" matInput [formControl]="query" [matAutocomplete]="autoGroup"/>
<mat-autocomplete #autoGroup="matAutocomplete">
<mat-optgroup *ngFor="let parents of filteredFoo$ | async" [label]="parents[0]">
<mat-option *ngFor="let data of parents[1]" [value]="data.data">
{{ data.data }}
</mat-option>
</mat-optgroup>
</mat-autocomplete>
Upvotes: 1