Home > Mobile >  Angular forms - remove validators after submit and reset
Angular forms - remove validators after submit and reset

Time:03-31

I have form in angular app. When I hit submit button the reset() function is triggered on form. After reset() all inputs are marked as they have errors. How can I reset form and not have validation errors after this action or how can i clean this validation errors after. I did try to cleanValidators() functions etc. nothing seems to work.

SUBMIT BUTON:

  <button mat-fab color="accent" type="submit">
    <mat-icon>add</mat-icon>
    Register
  </button>

SUBMIT PART:

this.service.createRecord(record).subscribe(response => {
  setTimeout(() => this.form.reset(), 500);
});

I did try something like this (and it don't work):

this.formControls.forEach(control=>{
   this.form.get(control)?.clearValidators();
   this.form.get(control)?.setValidators([Validators.required]);
   this.form.get(control)?.updateValueAndValidity();
});

CodePudding user response:

I'm currently learning angular so i think this is a good or or joosep.p answer .

this.registerForm.reset(); 
this.submitted = false;

CodePudding user response:

Simple reset should be enough without having to go over each control individually (looks like you intend to clear them all).

this.form.reset();

Example: https://stackblitz.com/edit/angular-reactive-form-validation-with-disable-and-tvbx3u?file=src/app/person-edit/person-edit.component.ts

  • Related