Angular Reset Form Builder

Overview

In this quick tutorial, we will reset a form after a successful submit has occurred. The fields will be cleared and the Validators will be reset.

In the component.ts file.

  constructor(private fb: FormBuilder,
              private yourSVC: YourService) { }

  dataForm = this.fb.group({
    ReportDate: [null, [Validators.required]],
    ActualCount: [null, [Validators.required, Validators.min(1)]]
  });

From the submit function use the reset() for the form. Then for each field use setErrors(null). This was the only way I was able to reset the validators in the form.  

  onSubmit($event): void {
this.yourSVC.addRecord(this.dataForm).subscribe((data) => {
      if (data.status === 202) {
        this.dataForm.reset();
        this.dataForm.controls.ReportDate.setErrors(null);
        this.dataForm.controls.ActualCount.setErrors(null);
      } else {
        this.openSnackBar(data.msg, 'Close', 'mat-warn');
      }
    },
    (err: HttpErrorResponse) => {
      console.log(err);
    });
  }

In this code snippet above the form is reset() and then each field has the error reset with errorReset(null).

this.dataForm.controls.fieldname.setErrors(null);

The clearValidators() function did not reset the validators. Each field needed to have the setError() set to null.

For clearing the form before submitting we can use a button of type clear. In the example below it becomes enabled when the form is pristine.

<button (click)="dataForm.reset()" type="reset" [disabled]="dataForm.pristine">Reset</button>