Form gets invalid after form.reset() - Angular2

Viewed 7433

I have a template based form in my Angular2 app for user registration. There, I am passing the form instance to the Submit function and I reset the from once the async call to the server is done.

Following are some important part from the form.

<form class="form-horizontal" #f="ngForm" novalidate (ngSubmit)="onSignUpFormSubmit(f.value, f.valid, newUserCreateForm, $event)" #newUserCreateForm="ngForm">

    <div class="form-group">
        <label class="control-label col-sm-3" for="first-name">First Name:</label>
        <div class="col-sm-9">
            <input type="text" class="form-control" placeholder="Your First Name" name="firstName" [(ngModel)]="_userCreateForm.firstName"
                #firstName="ngModel" required>
            <small [hidden]="firstName.valid || (firstName.pristine && !f.submitted)" class="text-danger">
               First Name is required !
            </small>
        </div>
    </div>

    .......

    .......

    <div class="form-group">
        <div class="col-sm-offset-3 col-sm-12">
            <button type="submit" class="btn btn-default">Submit</button>
            <button type="reset" class="btn btn-link">Reset</button>
        </div>
    </div>

</form>

In my component file, I have written following function.

onSignUpFormSubmit(model: UserCreateForm, isValid: boolean, form: FormGroup, event:Event) {

    event.preventDefault();

    if (isValid) {
        this._userEmail = model.email;

        this._authService.signUp(this._userCreateForm).subscribe(
            res => {
                console.log("In component res status = "+res.status);
                if(res.status == 201){
                    //user creation sucess, Go home or Login 
                    console.log("res status = 201");
                    this._status = 201;

                }else if(res.status == 409){
                    //there is a user for given email. conflict, Try again with a different email or reset password if you cannot remember
                    this._status = 409;
                }else{
                    //some thing has gone wrong, pls try again
                    this._serverError = true;
                    console.log("status code in server error = "+res.status);
                }

                form.reset();
                alert("async call done");
            }
        );
    }
}

If I submit an empty form, I get all validations working correctly. But, when I submit a valid form, Once the form submission and the async call to the server is done, I get all the fields of the form invalid again.

See the following screen captures.

enter image description here enter image description here

I cannot understand why this is happening. If I comment out form.reset(), I do not get the issue. But form contains old data i submitted.

How can I fix this issue?

7 Answers

I solved this By adding these lines:

function Submit(){
   ....
   ....
   // after submit to db

   // reset the form
  this.userForm.reset();

  // reset the errors of all the controls
  for (let name in this.userForm.controls) {
     this.userForm.controls[name].setErrors(null);
  }

}

You need to change the button type submit to button as following.

<div class="form-group">
    <div class="col-sm-offset-3 col-sm-12">
        <button type="button" class="btn btn-default">Submit</button>
        <button type="reset" class="btn btn-link">Reset</button>
    </div>
</div>

Reseting the form in simple javascript is the solution for now.

var form : HTMLFormElement = 
<HTMLFormElement>document.getElementById('id');
form.reset();

The solution:

TEMPLATE:

<form
  action=""
  [formGroup]="representativeForm"
  (submit)="register(myform)"
  #myform="ngForm"
>

*ngIf="registrationForm.get('companyName').errors?.required && myform.submitted"

COMPONENT:

register(form) {
  form.submitted = false;
}

Try changing the button type from "submit" to "button", e.g. :

<button type="button">Submit</button>

And move the submit method to click event of the button. Worked for me!

Related