Angular反应形式在重新加载/提交后显示错误

时间:2020-05-29 09:55:18

标签: angular typescript angular-reactive-forms angular-forms

我的组件中有一个Angular Form,允许用户向列表中添加电子邮件。这非常简单,提交视图后,将使用API​​调用重新加载电子邮件订户列表,然后用户可以添加另一封电子邮件...这是我模板中的HTML

<form [formGroup]="addEmailToListForm" (ngSubmit)="addEmailToList()"  autofill="off" novalidate>
    <div class="email-subscriber-list__control">
      <div class="email-subscriber-list__control__input">
        <mat-form-field>
          <input formControlName="email" matInput
                 placeholder="Subscriber"
                 autocomplete="off">
        </mat-form-field>
      <div>
        <button mat-raised-button color="primary" type="submit" [disabled]="!addEmailToListForm.valid">
          Add
        </button>
      </div>
    </div>
  </form>

现在,在我的组件代码文件中,我可以使用以下方法来创建表单并提交表单,仅在ngOnInit()

时运行创建
createAddEmailToListForm(): FormGroup {
    return new FormGroup({
      email: new FormControl('', [Validators.required, Validators.email],
        this.subscriberEmailUniqueValidator.validate.bind(this)
      )
    });
  }

  addEmailToList(): void {
    const data = {
      type: this.subscriptionType,
      subscriber: this.addEmailToListForm.controls['email'].value,
      tags: {
        company: this.selectedCompany
      }
    };

    const companyId = this.selectedCompany ? this.selectedCompany.id : null;

    this.apiService.createEmailSubscription(data, companyId).subscribe((resp: any) => {
        if (resp.message === 'Successfully created') {
         // reset the list and form item
          this.apiService
            .getEmailSubscriptions(this.subscriptionType, companyId).subscribe((emails) => {
            this.subscriptionList = emails;
          });
          this.addEmailToListForm.reset();
          this.addEmailToListForm.setErrors(null);
        }
      },
      (err) => {
        // do something...
      });
  }

这一切都很好,但是我注意到页面加载时<mat-form-field>没有显示错误状态,这很好。提交表单后,即使我使用<mat-form-field>reset()重设表单,.setErrors(null);仍显示错误状态(文本颜色和底部边框为红色),我尝试设置表单控件的错误为null,但这会删除验证程序(因此可以提交空值),或者如果我尝试执行markAsPristinemarkAsUntouched。我如何解决此问题的任何想法。下面的一些视觉效果可以帮助我解决问题

提交之前 enter image description here 提交后

0 个答案:

没有答案