我正在重置表单。它会重置整个表单,但FormArray除外。
创建表单并在其中声明formArray
createForm(){
this.invoiceForm = this.formBuilder.group({
'name': ['', Validators.required],
'gst': [''],
'currency': [''],
'addressLine1': ['', Validators.required],
'addressLine2': [''],
'city': ['', Validators.required],
'state': ['', Validators.required],
'country': ['', Validators.required],
'postalCode': ['', Validators.required],
'email': ['', [Validators.required, Validators.email]],
'invoiceparticulars': this.formBuilder.array([]),
'isGstshidden' : true
});
}
尝试通过重置数据来修改传入数据的表单细节,即使我调用了reset()函数formArray,也保留了之前的条目。
modifyInvoice(index){
this.invoiceForm.reset();
let modifyData = this.modifyInvoiceArray[index];
console.log(modifyData);
this.invoiceNumber = modifyData.invoiceNumber;
this.invoiceForm.patchValue({name: modifyData.address.Name});
this.invoiceForm.patchValue({email: modifyData.email});
this.invoiceForm.patchValue({gst: modifyData.GSTnumber});
this.invoiceForm.patchValue({addressLine1: modifyData.address.AddressLine1});
this.invoiceForm.patchValue({addressLine2: modifyData.address.AddressLine2});
this.invoiceForm.patchValue({city: modifyData.address.City});
this.invoiceForm.patchValue({country: modifyData.address.Country});
this.invoiceForm.patchValue({postalCode: modifyData.address.PostalCode});
this.invoiceForm.patchValue({state: modifyData.address.State});
console.log(modifyData['particulars']);
}
答案 0 :(得分:1)
尝试添加此代码
const control = <FormArray>this.invoiceForm.controls['invoiceparticulars'];
for(let i = control.length-1; i >= 0; i--) {
control.removeAt(i)
}
答案 1 :(得分:1)
角度8
仅在formArrays上使用clear()
方法:
(this.invoiceForm.controls['invoiceparticulars']).clear();
答案 2 :(得分:1)
从 Angular 8+ 开始,您可以使用 clear() 删除 FormArray 中的所有控件:
const arr = new FormArray([
new FormControl(),
new FormControl()
]);
console.log(arr.length); // 2
arr.clear();
console.log(arr.length); // 0