Cleanest way to reset forms
Asked Answered
W

16

93

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);
}
Whitford answered 6/1, 2017 at 6:22 Comment(0)
T
173

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.

Threewheeler answered 15/5, 2017 at 17:45 Comment(11)
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???Coahuila
@user1829319, I don't know what you mean by this not working anymore. If you follow this tutorial, near the bottom of the section (before this section), you will see that they reset the form exactly the way I have shown. You should see they initially had something like <form #heroForm="ngForm">, then later on they do <button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>. This is more or less the same thing.Threewheeler
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.Coahuila
@Coahuila Which reset method are you using? reset or resetForm?Threewheeler
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 daysPiscator
Maybe what @Coahuila means is that there is a bug making the input show the validation error even after calling ´form.reset()´ - github.com/angular/components/issues/4190Phototopography
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.Ureter
quick update: resetForm doesn't exist anymore. Now it's reset everywhereJoellyn
@Joellyn are you sure about that? Can you point to the appropriate documentation. I still see angular.io/api/forms/NgForm#resetformThreewheeler
yes resetForm() is there anymore :( ERROR TypeError: this.formGroup.resetForm is not a functionIncondite
@Incondite look carefully at the error you got. resetForm is a method on NgForm not FormGroup, if you are trying to reset a FormGroup, use reset, once again pay attention to what type of object you have.Threewheeler
S
33

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

Shaniceshanie answered 6/1, 2017 at 6:27 Comment(0)
F
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

Folacin answered 5/5, 2018 at 17:36 Comment(0)
A
10

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

UPDATE

The initialValueIsDefault option has been deprecated. Use nonNullable instead. Check out the documentation for further info: https://angular.dev/api/forms/FormControlOptions

Allmon answered 23/12, 2021 at 10:43 Comment(0)
W
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.

Wessex answered 14/9, 2018 at 12:38 Comment(0)
I
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

Idolatry answered 9/8, 2018 at 23:1 Comment(0)
V
3
this.<your_form>.form.markAsPristine();
this.<your_form>.form.markAsUntouched();
this.<your_form>.form.updateValueAndValidity();

can also help

Velarde answered 2/10, 2019 at 11:13 Comment(0)
C
3

Angular Reactive Forms:

onCancel(): void {
  this.registrationForm.reset();
  this.registrationForm.controls['name'].setErrors(null);
  this.registrationForm.controls['email'].setErrors(null);
}
Codfish answered 24/12, 2020 at 16:28 Comment(0)
J
2

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();
}
Junkie answered 14/8, 2019 at 9:46 Comment(0)
A
2

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!

Allmon answered 29/8, 2022 at 9:22 Comment(0)
C
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.

Catercornered answered 30/8, 2019 at 6:51 Comment(0)
F
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.

Foamy answered 12/10, 2021 at 12:21 Comment(0)
T
0

You can also do it through the JavaScript:

(document.querySelector("form_selector") as HTMLFormElement).reset();
Triphylite answered 13/5, 2018 at 8:22 Comment(2)
Sorry, it doesn't work, "Property 'reset' does not exist on type 'Element'.Rational
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!Triphylite
H
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": ''
    });
}
Hibbard answered 22/11, 2018 at 5:10 Comment(0)
M
0
    for (const key in this.someForm.controls) {
        this.someForm.get(key)?.clearValidators();
    }
    this.someForm.reset();
Mushro answered 3/3, 2023 at 8:21 Comment(0)
T
-5
    //Declare the jquery param on top after import
declare var $: any;
declare var jQuery: any;

clearForm() {
    $('#contactForm')[0].reset();
}
Tact answered 9/5, 2019 at 13:5 Comment(1)
Adding jquery into an angular application is frowned upon.Whitford

© 2022 - 2024 — McMap. All rights reserved.