Resetting a form in Angular is useful when you want to clear all form fields, reset the form state (valid, touched, etc.), or reset the values to their initial state. You can reset forms both in Template-driven forms and Reactive forms.
Let’s go through both approaches and how to reset forms in Angular.
1. Resetting Template-driven Forms
For Template-driven forms, you can reset the form using the reset()
method of the NgForm
object.
Example: Template-driven Form with Reset
app.component.html
(Template-driven Form)
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<label for="username">Username:</label>
<input type="text" id="username" name="username" [(ngModel)]="username" required #usernameField="ngModel" />
<label for="email">Email:</label>
<input type="email" id="email" name="email" [(ngModel)]="email" required email #emailField="ngModel" />
<button type="submit" [disabled]="!myForm.valid">Submit</button>
<!-- Reset button -->
<button type="button" (click)="resetForm(myForm)">Reset</button>
</form>
<p *ngIf="submitted">Form submitted!</p>
app.component.ts
(Component Code)
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
username: string = '';
email: string = '';
submitted: boolean = false;
onSubmit(form: any): void {
if (form.valid) {
this.submitted = true;
console.log('Form Data:', form.value);
}
}
resetForm(form: any): void {
form.reset(); // Reset the form values
this.submitted = false; // Reset the form submission state
}
}
Explanation:
- The form is declared with
#myForm="ngForm"
, which gives us access to the form object in the component. - When the “Reset” button is clicked, the
resetForm()
method is invoked, and it callsform.reset()
, which clears the form fields and resets the form state. reset()
restores the form fields to their initial state, and the form becomes “untouched” and “pristine.”
2. Resetting Reactive Forms
In Reactive forms, you manage the form and its controls using FormGroup
and FormControl
. To reset a reactive form, you can use the reset()
method of the FormGroup
instance.
Example: Reactive Form with Reset
app.component.html
(Reactive Form Template)
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
<label for="username">Username:</label>
<input id="username" formControlName="username" />
<label for="email">Email:</label>
<input id="email" formControlName="email" />
<button type="submit" [disabled]="formGroup.invalid">Submit</button>
<!-- Reset button -->
<button type="button" (click)="resetForm()">Reset</button>
</form>
<p *ngIf="submitted">Form submitted!</p>
app.component.ts
(Reactive Form Component)
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
formGroup: FormGroup;
submitted: boolean = false;
constructor(private fb: FormBuilder) {}
ngOnInit(): void {
// Initialize form with form controls and validators
this.formGroup = this.fb.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]]
});
}
onSubmit(): void {
if (this.formGroup.valid) {
this.submitted = true;
console.log('Form Data:', this.formGroup.value);
}
}
resetForm(): void {
this.formGroup.reset(); // Reset the form controls and values
this.submitted = false; // Reset the form submission state
}
}
Explanation:
- The
FormGroup
is created in thengOnInit()
lifecycle hook using theFormBuilder
service. - The form is bound to the template using
[formGroup]
, and individual controls are connected usingformControlName
. - The “Reset” button triggers the
resetForm()
method, which callsthis.formGroup.reset()
. reset()
clears the form fields and also resets the form state (i.e., marks the form as “untouched” and “pristine”).
3. Resetting Specific Form Controls
In both Template-driven and Reactive forms, you can reset specific controls if needed instead of resetting the entire form.
Resetting Specific Controls in Template-driven Forms
resetUsername(form: any): void {
form.controls['username'].reset(); // Only resets the 'username' field
}
Resetting Specific Controls in Reactive Forms
resetUsername(): void {
this.formGroup.get('username').reset(); // Only resets the 'username' control
}
4. Form Reset with Initial Values
Both approaches allow you to reset a form to its initial values. This is particularly useful if you want to restore the form to specific values after resetting it.
Template-driven Form with Initial Values:
resetForm(form: any): void {
form.reset({
username: 'Initial Username',
email: 'example@example.com'
});
}
Reactive Form with Initial Values:
resetForm(): void {
this.formGroup.reset({
username: 'Initial Username',
email: 'example@example.com'
});
}
5. Using reset
with Form Validation States
When you reset a form, its validation state also gets reset. The form and its controls become “pristine” and “untouched.”
Example of Validation States After Reset
resetForm(): void {
this.formGroup.reset(); // Resets form values and validation state
// Access form state
console.log('Form is pristine:', this.formGroup.pristine);
console.log('Form is touched:', this.formGroup.touched);
console.log('Form is valid:', this.formGroup.valid);
}
Conclusion
- Template-driven forms and Reactive forms both offer a simple way to reset forms using the
reset()
method. - The
reset()
method clears the form fields and resets the form’s state, making the form pristine and untouched. - You can reset the entire form or specific form controls.
- Optionally, you can reset the form to specific initial values when needed.
This makes it easy to manage form states and clear inputs, especially in scenarios where you want to allow users to reset a form without refreshing the entire page.