In my Angualar application I have a form with several text fields like order ID and order date. My form also has a FormArray where each element is a FormGroup representing a row of fields. This form array has 1 FormGroup at startup and more can be addedby clicking on a button. After I submit my form I want to reset the form after getting a succesful response from posting data to a REST service. My reset code form is as follows.:
resetItems(): void {
this.orderForm.reset();
this.clearErrorsFromFormGroup(this.orderForm);
let items = this.orderForm.get('items') as FormArray;
items.controls = [];
this.addItem();
this.clearErrorsFromFormGroup(items.at(0) as FormGroup);
}
private clearErrorsFromFormGroup(formGroup: FormGroup): void {
Object.keys(formGroup.controls).forEach(key => {
formGroup.controls[key].setErrors(null);
});
}
When executing the above the top level fields like order Id and Order date are reset and are not highlighted red as I have removed the errors. I want to set my form array to be the same way it was at start up with 1 element. My code clears the form array and adds a rowData Element. I then clear the errors for the rowData FormGroup. On the UI The fields for this rowData are all cleared but theys are highlighted red even though I have cleared the errors. Can anyone help please?
I have included a StackBlitz link to demonstrate this at https://stackblitz.com/edit/angular-8qjphu