vigamage
vigamage

Reputation: 2125

Form gets invalid after form.reset() - Angular2

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?

Upvotes: 11

Views: 9430

Answers (7)

Madhusha Ravishani
Madhusha Ravishani

Reputation: 41

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>

Upvotes: 1

abin_xavi
abin_xavi

Reputation: 1

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!

Upvotes: 0

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

Upvotes: 0

userx
userx

Reputation: 515

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

}

Upvotes: 4

christianAV
christianAV

Reputation: 149

this is how finally I had achieved this. I am using Angular5.

I have created a form group named ="firstFormGrop".

If you are not using form groups you can name the form as follow: <form #myNgForm="ngForm">

In the html doc:

<form [formGroup]="firstFormGroup">
<button mat-button (click)='$event.preventDefault();this.clearForm();'>
     <span class="font-medium">Create New</span>
</button>
</form>

In the .ts file:

this.model = new MyModel();
this.firstFormGroup.reset();

if you where using #myNgForm="ngForm then use instead:

myNgForm.reset();
// or this.myNgForm.reset()

This is a very common issue that after clicking the reset button we created the validators are not reset to its initial state, and it looks ugly.

To avoid that we have two options,the button is outside the form, or we prevent the submission when the button is tagged inside the form.

To prevent this default behaviour we need to call $event.preventDefault() before whatever method we are choosing to clear the form.

$event.preventDefault() is the key point.

Upvotes: 0

Laxmikanta Nayak
Laxmikanta Nayak

Reputation: 385

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

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

Upvotes: 0

lbrahim
lbrahim

Reputation: 3810

You can just initialize a new model to the property the form is bound to and set submitted = false like:

public onSignUpFormSubmit() {
    ...
    this.submitted = false;
    this._userCreateForm = new UserCreateForm();
}

Upvotes: 1

Related Questions