Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Reactive Form submit and clear validation

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?

like image 613
amitairos Avatar asked Jul 01 '18 15:07

amitairos


People also ask

How do you clear form after submit in angular?

import { FormsModule } from '@angular/forms'; In Reactive forms, we need to import FormGroup from '@angular/forms' . After importing the above-mentioned modules in the respective approach, angular forms module provides an inbuilt method called reset(). We can use the method and we can reset the form.

How reset angular form and set default values after submitting?

In a model-driven form to reset the form we just need to call the function reset() on our myform model. The form now resets, all the input fields go back to their initial state and any valid , touched or dirty properties are also reset to their starting values.

How do you add validation in reactive form?

In a reactive form, the source of truth is the component class. Instead of adding validators through attributes in the template, you add validator functions directly to the form control model in the component class. Angular then calls these functions whenever the value of the control changes.


2 Answers

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

like image 79
user184994 Avatar answered Oct 04 '22 06:10

user184994


This works, try this you need to reset the formDirective otherwise it will not 100% resting the form

Template:

<form 
  ...
  #formDirective="ngForm" 
>

Component:

import { ViewChild, ... } from '@angular/core';
import { NgForm, ... } from '@angular/forms';

export class MyComponent {
 ...
 @ViewChild('formDirective') private formDirective: NgForm;

  constructor(... )

  private someFunction(): void { 
    ...
    formDirective.resetForm();
  }
}
like image 26
Akitha_MJ Avatar answered Oct 04 '22 07:10

Akitha_MJ