我有一个来自我的API的array
,我使用Material2#AutoComplete过滤了这个...它到目前为止工作,但是我在无法在选项中显示另一个属性而不是绑定值。
我知道我必须使用displayWith
,但它并不像我期待的那样工作。名为[displayWith]="displayFn.bind(this)">
的函数只返回id
,如何获取完整对象,因此返回name
函数。
一些代码:
组件:
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;
}
}
模板:
<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>
基本上,它与this question几乎相同(不幸的是,两个答案都不正确或抛出错误)。
这里是PLUNKER。
答案 0 :(得分:14)
如果您希望整个对象与md-options
绑定,那么您应该绑定到state
的选项并在state.name
返回displayFn
,这样您就不会# 39; t必须绑定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;
}
<强> demo plunker 强>
如果您只想将state.id
绑定到md-options
,则必须循环浏览states
以基于state.name
查找state.id
并以此方式绑定<{1}}是必需的。
this
<强> demo plunker 强>