2016-04-22 32 views
2

各プラントにはプラントID、プラント名、役割があります。私はオプションの選択からオブジェクトの全体を元に戻そうとしています。角2は選択されたオプションを使用して選択されたオブジェクトの値を保持します

onChange(newValue){ 
     console.log(newValue) 
     this.selectedPlant = newValue 
    } 
<select 
    *ngIf="plants" 
    class="form-control" 
    style="width:auto;" 
    #sel 
    [(ngModel)]="selectedPlant" 
    (ngModelChange)="onChange($event)" 
    > 
    <option 
    *ngFor="#plant of plants" 
    [value]="plant.plantid" 
    >{{plant.plantname}}</option> 
</select> 

私は[value] = "plant", I get "[Object, Object]"を設定した場合。私はもう一方の値から一つの値を得るサービスを書くつもりですが、これを行うにはもっときれいな方法があるはずです。

答えて

1

あなたはプラント全体のオブジェクトを使用する場合は、あなたのコードの多くを変更することなく、あなたがthis-

onChange(plantid){ 
    console.log(plantid) 
    this.selectedPlant = this.plants.filter((plant)=>{ return plant.plantid=== plantid;}); 
} 

し、HTMLで行うことができます - 助け

<select *ngIf="plants" class="form-control" style="width:auto;" #sel (ngModel)]="selectedPlant" (ngModelChange)="onChange($event.target.value)"> 
<option *ngFor="#plant of plants" [value]="plant.plantid">{{plant.plantname}}</option> 

希望。あなたが代わりにプレーンな文字列の値としてオブジェクトを使用したい場合は

3

あなたは[value]の代わりに[ngValue]を使用する必要があります。

<select 
    *ngIf="plants" 
    class="form-control" 
    style="width:auto;" 
    #sel 
    [(ngModel)]="selectedPlant" 
    (ngModelChange)="onChange($event)"> 
    <option 
     *ngFor="let plant of plants" 
     [ngValue]="plant">{{plant.plantname}} 
    </option> 
</select> 
関連する問題