dev*_*054 11 autocomplete typescript angular-material2 angular
我有一个array来自我的API而且我正在使用Material2#AutoComplete过滤这个...它到目前为止工作,但是我很难显示另一个属性而不是选项中的绑定值.
我知道我必须使用displayWith它,但它不能像我期望的那样工作.调用的函数[displayWith]="displayFn.bind(this)">只返回我id,如何获取完整的对象,然后返回nameon函数.
顺便说一句,我仍然想在我的FormControl中绑定id .
一些代码:
零件:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
模板:
<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>
Run Code Online (Sandbox Code Playgroud)
基本上,它几乎与这个问题相同(不幸的是,两个答案都不正确或抛出错误).
这是PLUNKER.
Pen*_*gyy 18
如果你想要整个对象绑定md-options,那么你应该绑定到选项state和返回state.name,displayFn这样你就不必绑定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;
}
Run Code Online (Sandbox Code Playgroud)
如果你想只绑定state.id到md-options,你必须通过循环states找到state.name基于state.id这种方式的结合this是必要的.
<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>
displayFn(id) {
if (!id) return '';
let index = this.states.findIndex(state => state.id === id);
return this.states[index].name;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15742 次 |
| 最近记录: |