首页 > 解决方案 > 以角度方式提交后如何重置表单中的错误?

问题描述

我在表单中手动设置错误验证,使用setErrors.

问题是提交发生时错误不清楚。

我也不想遍历所有控件并将错误设置为 null- 因为它取消了控件上的其他错误。

只有一次我设置了错误,下次我不设置错误。我不想自己删除它我需要一些来自角度的功能来默认更新验证。

我尝试添加:{ updateOn: "submit" }不清除错误。角度应该知道他没有任何验证。所以第二次需要消除错误。所以这不会发生。

这是我的代码。如何更新/触发表单验证以消除错误?

import { Component } from "@angular/core";
import { FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: "app-root",
  template: `
    <form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
      <label>
        First Name:
        <input type="text" formControlName="firstName" required />
        <div *ngIf="firstname.hasError('foo')">foo error!!</div>
        <div *ngIf="firstname.hasError('required')">required</div>
      </label>

      <label>
        Last Name:
        <input type="text" formControlName="lastName" />
      </label>

      <button type="submit">submit</button>
    </form>
  `
})
export class AppComponent {
  title = "CodeSandbox";

  profileForm = new FormGroup({
    firstName: new FormControl(""),
    lastName: new FormControl("")
  });

  get firstname() {
    return this.profileForm.controls["firstName"];
  }

  showFooError = true;

  onSubmit() {
    console.log("in submit");

    if (this.showFooError) {
      this.profileForm.controls["firstName"].setErrors({ foo: true });
      this.showFooError = false;
    }
  }
}

标签: angular

解决方案


updateOn: 'blur'并且 updateOn: 'submit'是我们在使用 Angular 时真正渴望的选项Forms

所以试试这个:

app.component.ts

this.userForm = this.fb.group(
  {
    name: ["", [Validators.required]],
    email: ["", [Validators.required, Validators.email]]
  },
  { updateOn: "submit" }
);

或者

this.userForm = this.fb.group(
  {
    name: ["", [Validators.required]],
    email: ["", [Validators.required, Validators.email]]
  },
  { updateOn: "blur" }
);

有关更多信息,请参阅本文:模糊和提交的 Angular 表单验证


推荐阅读