89

What is the cleanest way to reset forms in Angular 2 latest version? I would like to reset the input textboxes after adding a post.

@Component({
  selector: 'post-div',
  template: `
            <h2>Posts</h2>
            <form (submit)="addPost()">
                <label>Title: </label><input type="text" name="title" [(ngModel)]="title"><br/>
                <label>Body: </label><input type="text" name="body" [(ngModel)]="body"><br/>
                <input type="submit" value="Add Post">
            </form>
            <ul>
                <li *ngFor="let post of posts">
                    <strong>{{post.title}}</strong>
                    <p>{{post.body}}</p>
                </li>
            </ul>
          `,
  providers: [PostService]
});

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

16 Answers 16

166

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.

11
  • 8
    This doesn't work anymore. Even in the angular sample -> angular.io/guide/form-validation if you press the "New Hero with reset " the 2nd time it will still show the "Name is required" validation error??? Steps are: Press the "New hero", type new values and press again "New hero". Validation errors shouldn't appear as form was reset??? Oct 19, 2017 at 1:54
  • 1
    Did you try their examples in the steps I explained? What i mean is if the form is reset and is pristine then you should not get the validation error. Oct 19, 2017 at 5:28
  • 3
    a reset will clear the entire form and move its state back to pristine (no validations fired), whereas a resetForm will just clear the values and not change the state, essentially 'textbox.clear' operations of previous days
    – NitinSingh
    May 1, 2018 at 9:44
  • 1
    Maybe what @user1829319 means is that there is a bug making the input show the validation error even after calling ´form.reset()´ - github.com/angular/components/issues/4190 Jun 12, 2019 at 3:47
  • 1
    To reset the whole form with its validations, you must go to resetForm() method. If you just wanna reset only the values, then use reset() method. Dec 11, 2019 at 9:14
32

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

12

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

8

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

7

Doing this with simple HTML and javascript by casting the HTML element so as to avoid typescript errors

<form id="Login">

and in the component.ts file,

clearForm(){
 (<HTMLFormElement>document.getElementById("Login")).reset();
}

the method clearForm() can be called anywhere as need be.

3

component.html (What you named you form)

<form [formGroup]="contactForm">

(add click event (click)="clearForm())

<button (click)="onSubmit()" (click)="clearForm()" type="submit" class="btn waves-light" mdbWavesEffect>Send<i class="fa fa-paper-plane-o ml-1"></i></button>

component.ts

 clearForm() {
             this.contactForm.reset();
            }

view all code: https://ewebdesigns.com.au/angular-6-contact-form/ How to add a contact form with firebase

2
this.<your_form>.form.markAsPristine();
this.<your_form>.form.markAsUntouched();
this.<your_form>.form.updateValueAndValidity();

can also help

2

Angular Reactive Forms:

onCancel(): void {
  this.registrationForm.reset();
  this.registrationForm.controls['name'].setErrors(null);
  this.registrationForm.controls['email'].setErrors(null);
}
1

For just to reset the form use reset() method. It resets the form but you could get issue such as validation errors - ex: Name is required

To solve this use resetForm() method. It resets the form and also resets the submit status solving your issue.

The resetForm() method is actually calling reset() method and additionally it is resetting the submit status.

0
1

The simplest method to clear a form with a button in angular2+ is

give your form a name using #

<form #your_form_name (ngSubmit)="submitData()"> </form>

<button (click)="clearForm(Your_form_name)"> clear form </button>

in your component.ts file

clearForm(form: FormGroup) {
form.reset();
}
1

There are many answers present here but no answer has passed arguments to reset function in NgForm.


You have to pass name of input fields with some values which will be initialized to the same default values which you passed by angular after resetting the form. Here is the form in HTML file

<form (ngSubmit)="onSubmit()" #f="ngForm">
    <label for="username">Username</label>
    <input type="text" ngModel name="username" required>

    <label for="email">Mail</label>
    <input type="email" ngModel name="email" required email>

    <label for="secret">Secret Questions</label>
    <select name="secret" ngModel>
        <option value="" disabled hidden selected>Select your option</option>
        <option value="pet">Your first Pet?</option>
        <option value="teacher">Your first teacher?</option>
    </select>

    <button type="button" (click)="reset()">Reset</button>
    <button type="submit">Submit</button>
</form>

Here is your .component.ts file

export class AppComponent {

    @ViewChild('f') signupForm: NgForm    // import { NgForm } from '@angular/forms';

    reset() {
        this.signupForm.reset({
            "username": "",
            "email": "",
            "secret": ""
        })
    }

    onSubmit() {
        console.log(this.signupForm.value)
    }
}

This is really helpful if you don't provide the default value for "secret" then the input box after pressing the reset button will become empty (""). There will be no default value that will be set to it. But now after resetting its default value will be set to "" so inside select field default value i.e. "Select your option" text will be seen. Note you can also omit any field if you don't want to give any default value to it.

1

As of Angular 14, forms are automatically typed using FormBuilder. When running:

this.contactForm.reset();

All the fields will be reset to null. But, if instead, we use NonNullableFormBuilder, all the fields will be reset to its original value. Very useful!

0

You can also do it through the JavaScript:

(document.querySelector("form_selector") as HTMLFormElement).reset();
2
  • Sorry, it doesn't work, "Property 'reset' does not exist on type 'Element'. May 14, 2018 at 4:53
  • 1
    Oh, sorry, indeed. In JavaScript it will work, but typescript doesn't know the type. I've updated the code. So, now compiler shoudn't display such an error. Thanks, that you mentioned it!
    – Igor
    May 14, 2018 at 8:40
0

To reset the form call the reset function with the form name in the same structure as like from group

addPost(){
    this.newPost = {
        title: this.title,
        body: this.body
    }
    this.formName.reset({
        "title": '',
        "body": ''
    });
}
0
    for (const key in this.someForm.controls) {
        this.someForm.get(key)?.clearValidators();
    }
    this.someForm.reset();
-5
    //Declare the jquery param on top after import
declare var $: any;
declare var jQuery: any;

clearForm() {
    $('#contactForm')[0].reset();
}
1
  • Adding jquery into an angular application is frowned upon. Jul 2, 2019 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.