Angular Reactive Form submit and clear validation

amitairos picture amitairos · Jul 1, 2018 · Viewed 14.9k times · Source

I have a reactive form

 <form [formGroup]="secondFormGroup">
      <ng-template matStepLabel>enter items</ng-template>
      <div style="display: flex; flex-direction: column;">
        <mat-form-field>
          <input matInput type="text" placeholder="category"  [(ngModel)]="newItem.CategoryName" formControlName="category"
          />
        </mat-form-field>
        <mat-form-field>
          <input matInput type="text" placeholder="sub category"  [(ngModel)]="newItem.SubCategoryName" formControlName="subCategory"
          />
        </mat-form-field>
        <mat-form-field>
          <input matInput type="text" placeholder="product"  [(ngModel)]="newItem.ProductName" formControlName="name"/>
        </mat-form-field>
        <mat-form-field>
          <input matInput  [(ngModel)]="newItem.Amount" type="number" min="0" placeholder="amount" formControlName="amount"
          />
        </mat-form-field>
        <mat-form-field>
          <input matInput  [(ngModel)]="newItem.Price" type="number" min="0" placeholder="price" formControlName="price"
          />
        </mat-form-field>
        <button mat-raised-button color="primary" (click)="AddNewProduct(newItem)" style="float: left; align-self: flex-end;">submit</button>
      </div>
    </form>

I initialize it like this:

 this.secondFormGroup = this._formBuilder.group({
  category: ['', Validators.required],
  subCategory: ['', Validators.required],
  name: ['', Validators.required],
  amount: ['', Validators.required],
  price: ['', Validators.required]
});

Upon clicking sumbit I call this method:

AddNewProduct(newProduct) {
if (this.secondFormGroup.valid) {
  //add product
  this.secondFormGroup.reset();
 } 
}

After adding the product, I clear the form. However, once the form is cleared, it triggers the validation errors. I want the validation errors to show only when the user clicks submit and the form isn't valid, not when I clear the form after submitting.

How can I fix this?

Answer

user184994 picture user184994 · Jul 1, 2018

The issue seems to be that the form is marked as submitted after reset is called. If the form is marked as submitted, regardless of whether or not its pristine, the errors will be highlighted.

You'll need to call resetForm instead, which is on the FormGroupDirective:

@ViewChild(FormGroupDirective) formGroupDirective: FormGroupDirective;

this.formGroupDirective.resetForm();

Secondly, you'll need to wrap it in a setTimeout with a timeout of 0, so that the form is submitted before it resets.

setTimeout(() => this.formGroupDirective.resetForm(), 0)

I've tested this in a StackBlitz, and it all seems to work:

https://stackblitz.com/edit/angular-l6xq1d?file=src%2Fapp%2Fapp.component.ts