Angular 2嵌套表单设置值

时间:2017-10-02 10:35:43

标签: angular angular2-formbuilder

我正在使用angular formbuilder来创建嵌套表单。如何在以下代码中为quantity函数中的每个表单组设置嵌套表单updateValue()字段值。

ngOnInit() {
   this.fastPostingForm = this.fb.group({
      Charges: this.fb.array([
        this.initCharge()
      ])
    });
}

initCharge(){
     return this.fb.group({
      room: ['', Validators.required],
      amount: ['', Validators.required],
      quantity: ['', Validators.required],
    });
 }

 UpdateValue(i) {
    this.fastPostingForm.controls.Charges[i].controls['quantity'].setValue(2); // This is not working
 }

1 个答案:

答案 0 :(得分:1)

应该是:

(this.fastPostingForm.controls.Charges as FormArray).controls[i].controls['quantity']
                                                    .setValue(2)

this.fastPostingForm.get(['Charges', i, 'quantity']).setValue(2);

this.fastPostingForm.get(`Charges.${i}.quantity`).setValue(2);
                        ^^^
                     backtick

或者您甚至可以在表单上使用patchValue方法:

this.fastPostingForm.patchValue({
  Charges: [...Array(i), { quantity: '2' }]
});