2017-02-22 84 views
1

我想创建自定义对象数据的Angular 2 MdAutocomplete,并且无法获取和设置对象数据。它过滤和显示,但没有绑定数据,它看起来不错,它不是在编辑表单上设置项目,并且在保存表单时没有获取项目。这里是我的模板和代码:角2 mdAutocomplete 2路数据绑定

**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) 

回答

-1
options: store[] = []; 

在构造

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()); 
} 
0

提供以下filterOptions要我understading的[formControl]指令是ReactiveForms的一部分,ngModel是做角方式全部在框架中。因此,既然你在混合两种方式角度工作与自动完成输入的形式,你必须手动做,如在被动的方式。

因此,这将是这样的:

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

为了使结合

希望它可以帮助