1

我正在尝试使用自定义对象数据创建 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)
4

2 回答 2

0

据我了解,该[formControl]指令是 ReactiveForms 的一部分,并且ngModel是 Angular 的方式在框架中完成这一切。因此,由于您将两种方式混合使用 Angular 和表单来自动完成输入,因此您必须像反应方式一样手动完成。

所以它会是这样的:

this.storeControl.valueChanges.subscribe(value => {this.store.card.name = value})

进行绑定

希望能帮助到你

于 2017-04-24T03:47:21.013 回答
-1
options: store[] = [];

在构造函数中提供以下 filterOptions

constructor(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());
}
于 2017-04-07T16:33:15.903 回答