我正在尝试使用自定义对象数据创建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)
答案 0 :(得分:0)
我认为[formControl]
指令是ReactiveForms的一部分,ngModel
是Angular方式在框架中完成所有操作。因此,既然你可以通过两种方式混合使用自动完成输入的表单,就必须像反应方式一样手动完成。
所以它会是这样的:
this.storeControl.valueChanges.subscribe(value => {this.store.card.name = value})
制作装订
希望有所帮助
答案 1 :(得分:-1)
options: store[] = [];
在构造函数
中提供以下filterOptionsconstructor(private storeService: StoreService) {
this.filteredOptions = this.myControl.valueChanges
.startWith(null)
.map(store=> store&& typeof store=== 'object' ? store.name: store)
.map(name=> name? this.filter(name) : this.options.slice());
}