0

HTML:

<form [formGroup]="locationForm" #myForm="ngForm" class="formContainer">

<div class="buttonContainer">
      <section class="btn1">
          <button 
          (click)="addAnotherMethod()"
          mat-raised-button 
          color="primary"> Add another method </button>
      </section>

      <section>
          <button
          (click)="addAnotherLocation()"
          mat-raised-button 
          color="primary"> Add another location </button>
      </section> 
    </div>

.TS File

@ViewChild('myForm') currentLocationForm;

addAnotherLocation(): void{
    if(this.locationForm.valid){
      //send data to redux
      }))
    }
    this.currentLocationForm.resetForm()
  }

addAnotherMethod: void {
    if(this.locationForm.valid){
     //send data to redux
      }))
    }
    this.currentLocationForm.resetForm()
  }

With the above code I'm able to reset the form after the data is sent to redux,but after reset, the validation error messages in the new form comes up saying to fill the required fields. I need help in using the correct method in resetting this form and clearing validations when new form is shown. I may be also using wrong method to call two button functions. Thank you.

PremKumar
  • 1,282
  • 4
  • 25
  • 43

2 Answers2

2

If you're looking to reset the form back to it's original state. Meaning before anything has been touched then Mark as Pristine would be your best bet.

Actually markAsPristine would do what you are expecting but also recalculate the validity based on the form values.

Reset is what would do both clear the form and mark it as it was never touched aka Pristine

So in code you would do something like.

this.locationForm.reset();

Which would mark the fromGroup and all it's children as pristine. This would effectively reset your form and should not have any validation errors.

Let me know if this helps!

Ex. https://angular-qv2mfx.stackblitz.io

Nico
  • 1,961
  • 17
  • 20
1

You have 2 things in your form: FormGroup and FormGroupDirective. To get the errors to go away, you need to reset both of them:

this.currentLocationForm.resetForm();
this.locationForm.reset();

See this post for more details about why.

Jesse
  • 2,391
  • 14
  • 15