Search code examples
angularformsvalidationresetformbuilder

Why do I get validation errors when resetting my form with FormBuilder?


I'm working in an angular 6 application. I'm working with FormBuilder. I've got a form that looks like this:

  <form [formGroup]="createInvitationForm" (ngSubmit)="createInvitation()">
    <mat-form-field class="full-width-input">
      <input matInput type="text" formControlName="invitationComment" placeholder="Send a comment to the group(s)." required>
      <mat-error *ngIf="createInvitationForm.get('invitationComment').hasError('required')">
        Invitation comment required
      </mat-error>
    </mat-form-field>
    <button mat-raised-button type="submit" color="primary" [disabled]="selectedGroups.length === 0 || !createInvitationForm.valid">Send invitation to selected group(s)</button>
  </form>

It's a very simple form. A text input and a submit button:

enter image description here

As you can see, I have a mat-error under the input that tells the user "Invitation comment required" if they don't enter a comment.

When the user hits submit, the invitation gets sent and I clear the form like so:

this.createInvitationForm.reset();

However, when I do this, the form looks like this:

enter image description here

In other words, the validation error now shows up.

In one sense, the mat-error is doing what it's supposed to do: when the form is reset, no data exists in the text input, which invalidates the form, so it displays the message. But in another sense, shouldn't it behave as if it were re-initialized (i.e. the form is not invalid upon initialization just because there's no data in the text input).

If my expectation of how reset() should work is off, please let me know a way to reset the form without invalidating it.

Thank you.


Solution

  • Thriller is close.

    It was this.createInvitationForm.controls['invitationComment'].setErrors(null);