0
votes

In my Angular application I have a form with several text fields as well as a FormArray where each element is a FormGroup representing a row of fields. This FormArray has 1 FormGroup at startup and more can be added by clicking on a button. Also the form has a submit button that should not be enabled until all fields are filled in. Upon submitting the form I want to call a Web Service and reset my form and remove field errors which I do successfully. However after form submission I click on the button to add a row to my FormArray and all the form fields for this new FormGroup are highlighted in red. The submit button is also enabled but I expect it to be disabled as all the form fields have not been filled in. Any idea on how to resolve this?

I have included a StackBlitz link to demonstrate this at https://stackblitz.com/edit/angular-ahnmv3

2

2 Answers

0
votes

Instead of reseting your form using the reset() method of the FormGroup class, use the resetForm() of the FormGroupDirective.

First you have to grab a reference to the FormGroupDirective. One way of doing that is putting a template reference variable on your form and passing it to your submit method:

<form [formGroup]="orderForm" #f="ngForm">
  ...

  <button (click)="submitForm(f)" 
          [disabled]="orderForm.invalid">
    Submit Form
  </button>

</form>

And in your ts file:

submitForm(f: FormGroupDirective): void {
  const items = this.orderForm.get("items") as FormArray;
  items.controls = [];
  this.addItem();

  f.resetForm(); // => instead of this.orderForm.reset()

  // There's no need to call the below method
  // this.clearErrorsFromFormGroup(this.orderForm);
}
0
votes

You have to just reinitialize the form after form submission. I forked your demo at stackblitz. You can see at https://stackblitz.com/edit/angular-g1fme8