My API returns an array
and I am using Material2#AutoComplete to filter it. While it is working, I am facing an issue where I need to display a different property instead of the currently binded value in the option element.
I understand that I need to utilize displayWith
, but I am not getting the expected result. The function
[displayWith]="displayFn.bind(this)"
only returns the id
value. How can I access the full object and display the name
instead within this function?
Additionally, I still require the id to be binded in my FormControl.
Some snippets from my code:
Component:
export class AutocompleteOverviewExample {
stateCtrl: FormControl;
filteredStates: any;
states = [
{
id: 1,
name: 'Alabama'
},
{
id: 2,
name: 'North Dakota'
},
{
id: 3,
name: 'Mississippi'
}
];
constructor() {
this.stateCtrl = new FormControl();
this.filteredStates = this.filterStates('');
}
onKeyUp(event: Event): void {
this.filteredStates = this.filterStates(event.target.value);
}
filterStates(val: string): Observable<any> {
let arr: any[];
console.log(val)
if (val) {
arr = this.states.filter(s => new RegExp(`^${val}`, 'gi').test(s.name));
} else {
arr = this.states;
}
// Simulates request
return Observable.of(arr);
}
displayFn(value) {
// I want to get the full object and display the name
return value;
}
}
Template:
<md-input-container>
<input mdInput placeholder="State" (keyup)="onKeyUp($event)" [mdAutocomplete]="auto" [formControl]="stateCtrl">
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn.bind(this)">
<md-option *ngFor="let state of filteredStates | async" [value]="state.id">
{{ state.name }}
</md-option>
</md-autocomplete>
It is similar to this question, but the answers provided are not working correctly.
Here is the PLUNKER for reference.