How to display with [displayWith] in Material2 autocomplete
I have array
one that comes from my API and I am using Material2 # AutoComplete to filter this ... it works so far, however I am having a hard time displaying another property instead of the bound value in the option.
I know what I need to use displayWith
, however it doesn't work as I expect. The function called [displayWith]="displayFn.bind(this)">
returns me id
how I can get the complete object and return the function name
.
By the way, I still want the ID to be bound in my FormControl .
Some codes:
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>
Basically, it's pretty much the same as this question (unfortunately, both answers are wrong or throw errors).
Here is PLUNKER .
source to share
If you want the entire object to bind to md-options
, you should bind to the option with state
and return state.name
to displayFn
, and that way you don't need to bind this
.
<md-autocomplete #auto="mdAutocomplete" [displayWith]="displayFn">
<md-option *ngFor="let state of filteredStates | async" [value]="state">
{{ state.name }}
</md-option>
</md-autocomplete>
displayFn(state) {
return state.name;
}
and if you only want to bind state.id
to md-options
, you have to go through states
to find state.name
based on state.id
, and thus binding is needed this
.
source to share