提交反应式表单后显示错误消息

时间:2020-04-14 21:56:21

标签: angular angular8 angular-reactive-forms

在Angular 8反应形式上,我具有以下内容:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
  <input id="name" type="text" formControlName="name">
  <span class="error" *ngIf="form.get('name').invalid && (form.get('name').dirty || form.get('name').touched)">
    Name error
  </span>
  <button type="submit" [disabled]="submitting">Send</button>
</form>

onSubmit是:

onSubmit() {

  this.submitting = true;

  if (this.form.valid) {
    // Submit form
  }

  this.submitting = false;

}

我正在尝试如下配置表单:

  1. 页面加载时错误消息不可见;

  2. 该字段的错误消息显示用户是否在该字段中键入了无效的内容;

  3. 错误消息显示是否提交了表单,并且该字段上存在错误。

    我希望即使表单无效也要提交。

我的问题是:

When the form is submitted, without touching the Name field, the error does not show after submission.

1 个答案:

答案 0 :(得分:1)

选项1:

您可以添加isSubmitted bool变量以指示用户是否按下了提交按钮,并在onSubmit()内将其值设置为true:

onSubmit() {
    this.isSubmitted = true;

    //rest of you code
}

并将ngIf设置为此:

<span *ngIf="(form.get('name').invalid && form.get('name').touched) || 
             (form.get('name').untouched && isSubmitted)">
    Not Valid
</span> 
  1. 页面加载时错误消息不可见;

第一行form.get('name').invalid && form.get('name').touched负责。

  1. 一个字段的错误消息显示用户是否在 字段;

默认情况下,Angular框架会执行此操作。

  1. 错误消息显示是否提交了表单,并且该字段上有错误。

第二行form.get('name').untouched && isSubmitted

选项2

就像这个伟大的article一样,提交后,您可以迭代所有控制器并将其设置为:

Object.keys(this.form.controls).forEach(field => {
    const control = this.form.get(field);
    control.markAsTouched({ onlySelf: true });
});

因此您可以使标记更整洁:

<span *ngIf="form.get('name').invalid && form.get('name').touched">
    Not Valid
</span>