如何从反应式表格中的其他formControl值自动更新formControl值2?

时间:2017-02-13 04:45:07

标签: arrays angular autocomplete angular-material2 reactive-forms

this.myForm = fb.group({
         name: ['', [Validators.required, Validators.minLength(2)]],
         date: ['', [Validators.required, Validators.minLength(2)]],
         address: ['', [Validators.required, Validators.minLength(2)]],
        ,
         items: fb.array([
             this.initItem(),
         ])
     });

initItem() {
  return this.fb.group({
      item: [''],
      itemType: [''],
      amount: [''],
      presentRate:this.myForm,
      total:['']
  });

提交表单时,此项属性将由对象存储。 示例对象:

item{
  itemName:"name",
  itemRate:1000,...}

我如何使用item对象的属性并修补我的initItem()方法属性中的值?我的场景是,当用户从下拉列表中选择一个值时,该项目将更新,我想显示值从其他formControls项目中获取。 例如:

<div *ngFor="let item of myForm.controls.items.controls; let i=index">
           <div [formGroupName]="i">
             <md2-autocomplete [items]="products"
                       item-text="product"
                       (change)="handleChange($event)"
                       placeholder="Product purchased"
                       formControlName="item"
                       >
             </md2-autocomplete>
             <md-input-container >
               <input md-input placeholder="Present rate" [value]="presentRate" formControlName="presentRate"  >
             </md-input-container>

我想自动更新presentRate输入框上的值。

2 个答案:

答案 0 :(得分:3)

您可以订阅表单控件的valueChanges,并在另一个表单控件上调用updateValueAndValidity

this.myForm.get('myControlName').valueChanges
.subscribe(val => 
  this.myForm.get('myOtherControlName').updateValueAndValidity(val)
);

答案 1 :(得分:2)

我假设您正在尝试根据presentRate中的所选值更新每个md2-autocomplete的值。如果我更正,以下内容应该有效:

<强>模板:

(change)="handleChange($event, i)"

<强>组件:

handleChange($event: any, i: index) {
  const control: AbstractControl = myForm.get(`items.${i}.presentRate`);
  let newVal: any;

  if ($event.value) {
    newVal = $event.value.rate;
  } else {
    newVal = '';
  }

  control.patchValue(newVal);
}