Cleanest way to reset forms Cleanest way to reset forms angular angular

Cleanest way to reset forms


Add a reference to the ngForm directive in your html code and this gives you access to the form.

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

Or pass the form to the 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

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