[angular] How to clear form after submit in Angular 2?

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>

This question is related to angular angular2-forms

The answer is


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>

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

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.


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.


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()


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


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/


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

resetForm(){
    ObjectName = {};
}

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".


this.myForm.reset();

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


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

}

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.


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. :)


Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Examples related to angular2-forms

How can I manually set an Angular form field as invalid? Angular 2 Cannot find control with unspecified name attribute on formArrays Remove all items from a FormArray in Angular Angular ReactiveForms: Producing an array of checkbox values? How to make readonly all inputs in some div in Angular2? tslint / codelyzer / ng lint error: "for (... in ...) statements must be filtered with an if statement" Min / Max Validator in Angular 2 Final TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" Can't bind to 'formGroup' since it isn't a known property of 'form' ngModel cannot be used to register form controls with a parent formGroup directive