为什么在使用 FormBuilder 重置表单时会出现验证错误?

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

我在 angular 6 应用程序中工作。我正在使用 FormBuilder。我有一个看起来像这样的表格:

  <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>

这是一个非常简单的表格。文本输入和提交按钮:

如您所见,我在输入下方有一个 mat-error,告诉用户 "Invitation comment required" 如果他们不输入评论。

当用户点击提交时,邀请被发送,我像这样清除表单:

this.createInvitationForm.reset();

但是,当我这样做时,表格看起来像这样:

换句话说,验证错误现在出现了。

从某种意义上说,mat-error 正在做它应该做的事情:重置表单时,文本输入中不存在任何数据,这会使表单无效,因此它会显示消息。但从另一个意义上说,它不应该表现得好像它被重新初始化一样吗(即表单在初始化时不是无效的,只是因为文本输入中没有数据)。

如果我对 reset() 的工作方式不满意,请告诉我一种重置表单而不使其失效的方法。

谢谢。

尝试添加以下部分this.createInvitationForm.setErrors(null);来重置表单控件的错误。

惊悚片即将上映。

它是 this.createInvitationForm.controls['invitationComment'].setErrors(null);