Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resetting reactive form triggers all required validators in Angular 6

I am new to angular 6 ,Here I am trying to reset the form after submitting the data.

Everything works fine but when I reset the form after successful data submit to database it triggers all the required validators in the form.

I tried many ways to solve this but I couldn't solve it .

Here after each form submission I want to reset the form and all the validators before enter the data in form fields for another submission.

app.component.html

<form [formGroup]="newMemberForm" (submit)="CreateMember(newMemberForm.value)" novalidate>
....
....
</form>

app.component.ts

            this.newMemberForm = this.formBuilder.group({
                  M_Number: ['', [Validators.required]],
                  F_Number: ['', [Validators.required]],
                  M_Name: ['', [Validators.required, Validators.minLength(4)]],
                  M_Status: ['', [Validators.required]],
                  M_Dob: ['', [Validators.required]],
                  M_Sex: ['', [Validators.required]],

                });

       CreateMember(memberForm) { 
        this.dmlService.CreateNewMember(memberForm).subscribe(data => {
              if (data[0]['RESPONSE'] == 'TRUE') 
         {
         this.newMemberForm.reset();
        }
       });
}

Here I have reset the form it triggers the required validatord.If I clears all the validators inside the above function ,When I enter another form data the validations are not working.

Here I want to reset all the validator and form after each form submission and I want to submit next set of form data .

can anyone help me to solve this .

like image 423
Zhu Avatar asked Jan 01 '23 17:01

Zhu


1 Answers

You would need to reset as below:

In your html:

<form [formGroup]="newMemberForm" #formDirective="ngForm"  
(submit)="CreateMember(newMemberForm.value,formDirective)" novalidate>

In .ts:

CreateMember(value,formDirective:FormGroupDirective){
 ...
 formDirective.resetForm();
 this.myForm.reset();
}

Material checks the validity of FormGroupDirective and not of FormGroup hence resetting FormGroup does not reset FormGroupDirective.

Issue reported here too: https://github.com/angular/material2/issues/9347

like image 57
User3250 Avatar answered Jan 04 '23 06:01

User3250