I have an array
that comes from my API and I'm using Material2#AutoComplete to filter this... it's working so far, however I'm in trouble to display the another property instead of the binded value in option.
I know I have to use displayWith
, however it isn't working as I'm expecting. The function called as [displayWith]="displayFn.bind(this)">
just returns me the id
, how can I get the full object and so return the name
on function.
BTW, I still want to have the id binded in my FormControl.
Some 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>
Basically, it's almost the same as this question (unfortunately both answers are incorrect or throw errors).
Here's the PLUNKER.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…