2017-08-10 8 views
0

私は角度4を初めて使用し、選択フィールド内で選択された内容に基づいて入力フィールドに情報を表示しようとしています。角4 - 反応型は配列の結果を得ます

<select 
    formControlName="selectCar" 
    class="form-field"> 
    <option value="">Pick a car</option> 
    <option *ngFor="let car of carOptions" [value]="car.value">{{car.name}}</option> 
</select> 

上記の選択には問題はありません。私はドロップダウンリストから車を選ぶことができます。データは、以下の配列から来ている:

readonly carOptions = [ 
    { 
     value: 'HYUNDAI_I20_BLUE', 
     name: 'Hyundai i20 blue', 
     price: 250, 
     currency: 'EUR' 
    }, 
    { 
     value: 'HYUNDAI_I20_RED', 
     name: 'Hyundai i20 red', 
     price: 275, 
     currency: 'EUR' 
    } 
]; 

しかし、私がやりたいことは、私はこれをやって行くのですか、単に選択された車の価格と通貨で下の2つの入力フィールドを入力するのですか?だから、最終的なコードは次のようになります。

ヘルプははるかに高く評価されるだろう
<select 
    formControlName="selectCar" 
    class="form-field"> 
    <option value="">Pick a car</option> 
    <option *ngFor="let car of carOptions" [value]="car.value">{{car.name}}</option> 
</select> 
price: <input type="text" value="250"> 
currency: <input type="text" value="EUR"> 

答えて

0

はあなたを行い、選択した値を表示します既にオプションの選択を処理するコードがありますか?

その場合は、setValueまたはpatchValueを使用してフォーム上のデータを更新できます。これは私が私のアプリから自分のフィールドに合わせた例です。

ngOnInit方法で:

this.myForm.get('selectCar') 
      .valueChanges 
      .subscribe(value => this.updateControls(value)); 

コンポーネント内の別の方法:

updateControls(value) { 
    this.myForm.get('price').setValue(value.price); 
    this.myForm.get('currency').setValue(value.currency); 
} 

注:これは、あなたが追加する必要がフォームへの2つの入力要素:

price: <input type="text" value="250" formControlName="price"> 
currency: <input type="text" value="EUR" formControlName="currency"> 
-1

1)バインド選択した値

<select [(ngModel)]="selectedValue" 
    formControlName="selectCar" 
    class="form-field"> 

2)

price: <input type="text" value="250" [(ngModel)]="selectedValue.price"> 
currency: <input type="text" value="EUR" [(ngModel)]="selectedValue.currency"> 
+0

感謝を参照してください、私はngModel SBOUT考えていたが、イマイチ:

<select (change)="onChange($event.target.value)" class="form-field"> <option value="">Pick a car</option> <option *ngFor="let car of carOptions" [value]="car.value">{{car.name}}</option> </select> price: <input type="text" [value]="price"> currency: <input type="text" [value]="currency"> 

は、次に選択が変更されたときに、値を設定しましたフォーム? – Ronald

+0

'ngModel'は反応性のあるフォームでは使用しないでください。 – DeborahK

+0

ごめんなさい –

0

選択して入力値を設定します。あなたが反応を使用しているとき、それは倍増

onChange(selectedCar) { 
    const car = this.carOptions.find(c => c.value === selectedCar); 
    this.price = car.price + ''; 
    this.currency = car.currency; 
} 

はあなたの応答のために、このplunker

関連する問題