我是Angular 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'
    }
];但是我想要做的是用刚才选择的汽车的价格和货币填充下面的两个输入字段,我该怎么做呢?所以最终的代码可能是:
<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">如果能帮上忙,我们将不胜感激。
发布于 2017-08-11 03:26:22
你已经有处理选项选择的代码了吗?
如果是,则可以在该例程中使用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);
}注意:这要求您还将两个输入元素添加到表单:
price: <input type="text" value="250" formControlName="price">
currency: <input type="text" value="EUR" formControlName="currency">发布于 2017-08-11 03:37:29
监听select发出的更改事件,并设置输入的值。
<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">然后在更改select时设置值:
onChange(selectedCar) {
    const car = this.carOptions.find(c => c.value === selectedCar);
    this.price = car.price + '';
    this.currency = car.currency;
}查看此plunker
发布于 2017-08-11 03:17:14
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">https://stackoverflow.com/questions/45621777
复制相似问题