How to clear form after submit in Angular 2?

AngularAngular2 Forms

Angular Problem Overview


I have some simple angular 2 component with template. How to clear form and all fields after submit?. I can't reload page. After set data with date.setValue('') field is stil touched.

import {Component} from 'angular2/core';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, Control} from 'angular2/common';

@Component({
    selector: 'loading-form',
    templateUrl: 'app/loadings/loading-form.component.html',
    directives: [FORM_DIRECTIVES]
})

export class LoadingFormComponent {
    private form:ControlGroup;
    private date:Control;
    private capacity:Control;

    constructor(private _loadingsService:LoadingsService, fb:FormBuilder) {
        this.date = new Control('', Validators.required);
        this.capacity = new Control('', Validators.required);
        this.form = fb.group({
            'date': this.date,
            'capacity': this.capacity
        });
    }

    onSubmit(value:any):void {
        //send some data to backend
    }
}

loading-form.component.html

<div class="card card-block">
    <h3 class="card-title">Loading form</h3>

    <form (ngSubmit)="onSubmit(form.value)" [ngFormModel]="form">
        <fieldset class="form-group" [class.has-danger]="!date.valid && date.touched">
            <label class="form-control-label" for="dateInput">Date</label>
            <input type="text" class="form-control form-control-danger form-control-success" id="dateInput"
                   min="0" placeholder="Enter loading date"
                   [ngFormControl]="form.controls['date']">
        </fieldset>
        <fieldset class="form-group" [class.has-danger]="!capacity.valid && capacity.touched">
            <label class="form-control-label" for="capacityInput">Capacity</label>
            <input type="number" class="form-control form-control-danger form-control-success" id="capacityInput"
                   placeholder="Enter capacity"
                   [ngFormControl]="form.controls['capacity']">
        </fieldset>
        <button type="submit" class="btn btn-primary" [disabled]="!form.valid">Submit
        </button>
    </form>
</div>

Angular Solutions


Solution 1 - Angular

See also https://angular.io/docs/ts/latest/guide/reactive-forms.html (section "reset the form flags")

>=RC.6

In RC.6 it should be supported to update the form model. Creating a new form group and assigning to myForm

[formGroup]="myForm"

will also be supported (https://github.com/angular/angular/pull/11051#issuecomment-243483654)

>=RC.5

form.reset();

In the new forms module (>= RC.5) NgForm has a reset() method and also supports a forms reset event. https://github.com/angular/angular/blob/6fd5bc075d70879c487c0188f6cd5b148e72a4dd/modules/%40angular/forms/src/directives/ng_form.ts#L179

<=RC.3

This will work:

onSubmit(value:any):void {
  //send some data to backend
  for(var name in form.controls) {
    (<Control>form.controls[name]).updateValue('');
    /*(<FormControl>form.controls[name]).updateValue('');*/ this should work in RC4 if `Control` is not working, working same in my case
    form.controls[name].setErrors(null);
  }
}

See also

Solution 2 - Angular

As of Angular2 RC5, myFormGroup.reset() seems to do the trick.

Solution 3 - Angular

To reset your form after submitting, you can just simply invoke this.form.reset(). By calling reset() it will:

  1. Mark the control and child controls as pristine.
  2. Mark the control and child controls as untouched.
  3. Set the value of control and child controls to custom value or null.
  4. Update value/validity/errors of affected parties.

Please find this pull request for a detailed answer. FYI, this PR has already been merged to 2.0.0.

Hopefully this can be helpful and let me know if you have any other questions in regards to Angular2 Forms.

Solution 4 - Angular

Make a Call clearForm(); in your .ts file

Try like below example code snippet to clear your form data.

clearForm() {
       
this.addContactForm.reset({
	  'first_name': '',
      'last_name': '',
      'mobile': '',
      'address': '',
	  'city': '',
      'state': '',
      'country': '',
       'zip': ''
	 });
}

Solution 5 - Angular

Here is how I do it in Angular 7.3

// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {

	form.reset();

	Object.keys(form.controls).forEach(key => {
	  form.get(key).setErrors(null) ;
	});
}

There was no need to call form.clearValidators()

Solution 6 - Angular

Here's how I do it Angular 8:

Get a local reference of your form:

<form name="myForm" #myForm="ngForm"></form>
@ViewChild('myForm', {static: false}) myForm: NgForm;

And whenever you need to reset the form, call resetForm method:

this.myForm.resetForm();

You will need FormsModule from @angular/forms for it to work. Be sure to add it to your module imports.

Solution 7 - Angular

import {Component} from '@angular/core';
import {NgForm} from '@angular/forms';
@Component({
    selector: 'example-app',
    template: '<form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
        <input name="first" ngModel required #first="ngModel">
        <input name="last" ngModel>
        <button>Submit</button>
    </form>
    <p>First name value: {{ first.value }}</p>
    <p>First name valid: {{ first.valid }}</p>
    <p>Form value: {{ f.value | json }}</p>
    <p>Form valid: {{ f.valid }}</p>',
})
export class SimpleFormComp {
    onSubmit(f: NgForm) {
        
        // some stuff

        f.resetForm();
    }
}

Solution 8 - Angular

To angular version 4, you can use this:

this.heroForm.reset();

But, you could need a initial value like:

ngOnChanges() {
 this.heroForm.reset({
  name: this.hero.name, //Or '' to empty initial value. 
  address: this.hero.addresses[0] || new Address()
 });
}

It is important to resolve null problem in your object reference.

reference link, Search for "reset the form flags".

Solution 9 - Angular

this.myForm.reset();

This is all enough...You can get the desired output

Solution 10 - Angular

There is a new discussion about this (https://github.com/angular/angular/issues/4933). So far there is only some hacks that allows to clear the form, like recreating the whole form after submitting: https://embed.plnkr.co/kMPjjJ1TWuYGVNlnQXrU/

Solution 11 - Angular

I found another solution. It's a bit hacky but its widely available in angular2 world.

Since *ngIf directive removes the form and recreates it, one can simply add an *ngIf to the form and bind it to some sort of formSuccessfullySentvariable. => This will recreate the form and therefore reset the input control statuses.

Of course, you have to clear the model variables also. I found it convenient to have a specific model class for my form fields. This way i can reset all fields as simple as creating a new instance of this model class. :)

Solution 12 - Angular

To reset the complete form upon submission, you can use reset() in Angular. The below example is implemented in Angular 8. Below is a Subscribe form where we are taking email as an input.

<form class="form" id="subscribe-form" data-response-message-animation="slide-in-left" #subscribeForm="ngForm"
(ngSubmit)="subscribe(subscribeForm.value); subscribeForm.reset()">
<div class="input-group">
   <input type="email" name="email" id="sub_email" class="form-control rounded-circle-left"
      placeholder="Enter your email" required ngModel #email="ngModel" email>
   <div class="input-group-append">
      <button class="btn btn-rounded btn-dark" type="submit" id="register"
         [disabled]="!subscribeForm.valid">Register</button>
   </div>
</div>
</form>

Refer official doc: https://angular.io/guide/forms#show-and-hide-validation-error-messages.

Solution 13 - Angular

Hm, now (23 Jan 2017 with angular 2.4.3) I made it work like this:

newHero() {
    return this.model = new Hero(42, 'APPLIED VALUE', '');
}
<button type="button" class="btn btn-default" (click)="heroForm.resetForm(newHero())">New Hero</button>

Solution 14 - Angular

Below code works for me in Angular 4

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
 registerForm: FormGroup; 

 constructor(private formBuilder: FormBuilder) { }   

 ngOnInit() {
    this.registerForm = this.formBuilder.group({
      empname: [''],
      empemail: ['']
    });
 }

 onRegister(){
    //sending data to server using http request
    this.registerForm.reset()
 }

}

Solution 15 - Angular

resetForm(){
    ObjectName = {};
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmasel.popowoView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - Angularebhh2001View Answer on Stackoverflow
Solution 3 - AngularJayKanView Answer on Stackoverflow
Solution 4 - Angularmkumar0304View Answer on Stackoverflow
Solution 5 - AngularMauricio Gracia GutierrezView Answer on Stackoverflow
Solution 6 - AngularSinandroView Answer on Stackoverflow
Solution 7 - AngularRahul TiwariView Answer on Stackoverflow
Solution 8 - AngularLucas SelliachView Answer on Stackoverflow
Solution 9 - AngularManikanta SaiView Answer on Stackoverflow
Solution 10 - AngularwawkaView Answer on Stackoverflow
Solution 11 - AngularBenjamin JesuiterView Answer on Stackoverflow
Solution 12 - AngularAbhishek AggarwalView Answer on Stackoverflow
Solution 13 - AngularAdrianView Answer on Stackoverflow
Solution 14 - AngularThavaprakash SwaminathanView Answer on Stackoverflow
Solution 15 - AngularShivendraView Answer on Stackoverflow