0

I want to submit and reset a form after validation .

validation and submition and init of inputs values works good, but validators won't be reseted.

here is the result after form submittion

enter image description here

Register the control in the template :

    <form [formGroup]="createSeanceForm" #formDirective="ngForm"  class="needs-validation" (ngSubmit)="createSeance(createSeanceForm, formDirective)">

My input and how i show errors :

<div class="col-sm-12 ">
       <div class="form-group" [ngClass]="{
            'has-success': (submitted  || f.date.touched || f.date.dirty) &&  f.date.valid ,
            'has-danger': (submitted || f.date.touched || f.date.dirty) &&  f.date.invalid
                                                                        }">
           <input type="datetime-local" class="form-control" formControlName="date" placeholder="Date de la visite">
       </div>

     <div *ngIf="submitted && f.date.errors" class="invalid-feedback">
       <small class="text-danger ml-3 my-1" *ngIf="f.date.errors.required">Merci de renseigner ce champ !</small>

    </div>

My imports :

 import { FormBuilder, FormGroup, Validators, FormGroupDirective } from '@angular/forms';

My constructor and formGroup declaration:

createSeanceForm: FormGroup;

    constructor( 
    ...
        private formBuilder: FormBuilder
        ) { 
           
           
          this.initSeanceForm();

        }

My InitForm :

initSeanceForm() {
    this.createSeanceForm = this.formBuilder.group({
    date: ['', Validators.required],
    act: ['', Validators.required],
    doctor: ['', [Validators.required]],
    price: ['',],
    teeth: ['',]
    //teeth: ['', [Validators.required]]
});
  }

  get f() { return this.createSeanceForm.controls; }

Submit and reset Function

 createSeance(myForm, formDirective: FormGroupDirective){    

      this.submitted = true;
        
      // stop here if form is invalid
      if (this.createSeanceForm.invalid) {
          return;
      }else{
     TODO : API stuff.

       formDirective.resetForm();
       this.createSeanceForm.reset();
       this.createSeanceForm.markAsPristine();
       this.createSeanceForm.markAsUntouched();

        $('#addSeanceModal').modal('hide')
    }
mehdi
  • 119
  • 1
  • 11
  • Do you want to remove validation from the controls? Or do you want to hide the validation messages when the form gets resetted? – Nithya Rajan Feb 26 '19 at 18:19
  • yes, why the errors messages are dispayed before touching or submiting the form for the second time. NB : the first submition action is ok : it control inputs and submit data, after first submition it shows errors – mehdi Feb 26 '19 at 18:33
  • Actually, you want to remove the validators once the form is submitted.? – Nithya Rajan Feb 26 '19 at 18:45
  • Exactly, to not affect other submit action – mehdi Feb 26 '19 at 19:02

0 Answers0