bmrki
bmrki

Reputation: 501

Angular forms - remove validators after submit and reset

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();
});

[UPDATE]

Ok, I'll show print screens. So this is my start point (after page is loaded):

enter image description here

then I'm clicking "Submit" button -> this triggers 'this.form.reset()`, after that it looks like this:

enter image description here

Nothing happens between, why this input is marked red?

This is how i declare form:

<mat-form-field appearance="outline" class="form-field">
    <mat-label>Name</mat-label>
    <input matInput formControlName="Name" type="text" autocomplete="off" required/>
    <mat-error>{{'validation.requiredError' | translate}}</mat-error>
</mat-form-field>
<div>pristine: {{ visitForm.get("Name")?.pristine }}</div>
<div>touched: {{ visitForm.get("Name")?.touched }}</div>
<div>valid: {{ visitForm.get("Name")?.valid }}</div>
<div>disabled: {{ visitForm.get("Name")?.disabled}}</div>
this.form = new FormGroup({ 
    Autocomplete: new FormControl(), 
    Name: new FormControl('', Validators.required), 
    Surname: new FormControl('', Validators.required), 
});

Upvotes: 2

Views: 4494

Answers (1)

Joosep Parts
Joosep Parts

Reputation: 6225

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%2Fapp%2Fperson-edit%2Fperson-edit.component.ts

Upvotes: 0

Related Questions