Resetting Angular ReactiveForms validators

Angulars Reactive Forms are an awesome way to easily handle simple or complicated forms. A common issue many Angular developers are facing is resetting these forms within the component class without resetting the form Validations.
Imagine a very simple form for posting comments in a guestbook or whatever. After submitting the data the form should be resetted without any Validation errors left.
The template for example could look like this:
<form [formGroup]="commentsForm" (ngSubmit)="save()"> <textarea matInput placeholder="Comment" formControlName="message"></textarea> <button color="primary" [disabled]="!commentsForm.valid"><mat-icon>send</mat-icon> Submit</button> </form>
This form contains a textarea for the comment and a submit button. Now think about a component class like this
import { Component, OnInit, ViewChild } from '@angular/core'; import { Store } from '@ngrx/store'; import { Observable } from 'rxjs'; import * as fromFeature from '../store'; import * as fromAuth from '../../auth/store'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-comments-form', template: `<!-- paste code snippet 1 here -->` }) export class CommentsFormComponent implements OnInit { commentsForm: FormGroup; constructor() { this.commentsForm = new FormGroup({ message: new FormControl(null, Validators.required) }); } save() { const comment = this.commentsForm.value; // work with comment. this.commentsForm.reset(); // Just resets the form without resetting form validation } }
This successfully removes all the data from the form, but it just resets the Angular FormGroup, but not the DOMs HTML element. For this reason one has to create a @ViewChild pointing to the form tag.
@ViewChild('formRef') formRef;
Afterwards add a #formRef id to the templates form tag. Pay attention to leave the existing directives as they are.
<form #formRef="ngForm"></form>
Resetting the form is now as simple as
this.commentsForm.reset(); // Clears the Angular FormGroup without clearing validators. this.formRef.resetForm(); // Clears the DOM form with validators
Submitting the form now leads to a cleared form without any validation errors left.

Comments

Any questions? Want to join the discussion?

Sign in or sign up