Angular 2个嵌套表单设置值

Angular 2 nested form set value

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

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
 }

应该是:

(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' }]
});