首页 文章

Angular 2嵌套表单设置值

提问于
浏览
1

我正在使用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
 }

1 回答

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

相关问题