我正在尝试使用自定义对象数据创建 Angular 2 MdAutocomplete,但无法获取和设置对象数据。过滤和显示看起来不错,但不绑定数据,它不是在编辑表单上设置项目,也不是在保存表单时获取项目。这是我的模板和代码:
**HTML:**
*<md-input-container>
<input type="text" required placeholder="Store" mdInput [formControl]="storeControl" [mdAutocomplete]="auto" [value]="card.store.name">
<md-hint *ngIf="card.store == null || card.store.id == 0" [ngStyle]="{'color': 'red'}"> Store is required </md-hint>
</md-input-container>
<md-autocomplete #auto="mdAutocomplete" name="store" [(ngModel)]="card.store" [displayWith]="displayFn" ngDefaultControl>
<md-option *ngFor="let store of filteredStores | async" [value]="store">
{{ store?.name }}
</md-option>
</md-autocomplete>*
**TS**
*private stores: Store[];
filteredStores: Observable<Store[]>;
private card:Card = <Card> {
store: new Store(0,'',''),
};
storeControl = new FormControl();
ngOnInit() {
this.storeService.getStores().subscribe(result => {
this.stores = result.items;
});
this.filteredStores = this.storeControl.valueChanges
.startWith(null)
.map(name => name ? this.filter(name) : this.stores);
}
filter(name: string): Store[] {
return this.stores.filter(store => new RegExp(name, 'gi').test(store.name));
}
displayFn(store: Store): string {
if (store != null) {
this.card.store = store;
}
return store ? store.name : '';
}*
Object Item: Store(id, name, description)