我正在使用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
}
答案 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' }]
});