Cleanest way to reset forms
AngularFormsAngular Problem Overview
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);
}
Angular Solutions
Solution 1 - Angular
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.
Solution 2 - Angular
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
Solution 3 - Angular
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
Solution 4 - Angular
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.
Solution 5 - Angular
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
Solution 6 - Angular
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
Solution 7 - Angular
Angular Reactive Forms:
onCancel(): void {
this.registrationForm.reset();
this.registrationForm.controls['name'].setErrors(null);
this.registrationForm.controls['email'].setErrors(null);
}
Solution 8 - Angular
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();
}
Solution 9 - Angular
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.
Solution 10 - Angular
this.<your_form>.form.markAsPristine();
this.<your_form>.form.markAsUntouched();
this.<your_form>.form.updateValueAndValidity();
can also help
Solution 11 - Angular
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.
Solution 12 - Angular
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": ''
});
}
Solution 13 - Angular
You can also do it through the JavaScript:
(document.querySelector("form_selector") as HTMLFormElement).reset();
Solution 14 - Angular
//Declare the jquery param on top after import
declare var $: any;
declare var jQuery: any;
clearForm() {
$('#contactForm')[0].reset();
}