Cleanest way to reset forms

In Angular 13 an interesting feature was added: When creating a form control you can use the initialValueIsDefault option, so when using reset() the value of the form will be set to its initial value.

I find this really useful with bigger forms, if you have a reset button or similar logic.

For more information here is the feature PR on GitHub: https://github.com/angular/angular/pull/44434


Add a reference to the ngForm directive in your html code and this gives you access to the form, so you can use .resetForm().

<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.resetForm()"> ... </form>

...Or pass the form to a function:

<form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
addPost(form: NgForm){
    this.newPost = {
        title: this.title,
        body: this.body
    }
    this._postService.addPost(this.newPost);
    form.resetForm(); // or form.reset();
}

The difference between resetForm and reset is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.


Adding another example for people who can't get the above to work.

With button press:

<form #heroForm="ngForm">
    ...
    <button type="button" class="btn btn-default" (click)="newHero(); heroForm.resetForm()">New Hero</button>
</form>

Same thing applies above, you can also choose to pass the form to the newHero function.


Easiest and cleanest way to clear forms as well as their error states (dirty, pristine etc)

this.formName.reset();

for more info on forms read out here

  • https://angular.io/docs/ts/latest/guide/forms.html

PS: As you asked a question there is no form used in your question code you are using simple two-day data binding using ngModel, not with formControl.

form.reset() method works only for formControls reset call


easiest way to clear form

<form #myForm="ngForm" (submit)="addPost();"> ... </form>

then in .ts file you need to access local variable of template i.e

@ViewChild('myForm') mytemplateForm : ngForm; //import { NgForm } from '@angular/forms';

for resetting values and state(pristine,touched..) do the following

addPost(){
this.newPost = {
    title: this.mytemplateForm.value.title,
    body: this.mytemplateForm.value.body
}
this._postService.addPost(this.newPost);
this.mytemplateForm.reset(); }

This is most cleanest way to clear the form

Tags:

Forms

Angular