【问题标题】:Angular- Reactive Forms: How to validate fields after patchValueAngular-Reactive Forms:如何在 patchValue 之后验证字段
【发布时间】:2021-04-27 19:04:07
【问题描述】:

我有一个使用 ControlValueAccessor 的带有子表单的表单

profile-form.component.ts

form: FormGroup;
this.form = this.formBuilder.group({
        firstName: [],
        lastName: ["", Validators.maxLength(10)],
        email: ["", Validators.required]
      });

get lastNameControl() {
    return this.form.controls.lastName;
  }

initForm() {
    ...
       this.form.patchValue({
        firstName: "thompson",
        lastName: "vilaaaaaaaaaaaaaaaaaaaa",
        email: "abc@gmail.com"
      });
    ...
  }

profile-form.component.html

<label for="last-name">Last Name</label>
    <input formControlName="lastName" id="last-name" />
    <div *ngIf="lastNameControl.touched && lastNameControl.invalid" class="error">
      last name max length is 10
    </div>

问题:

初始数据已加载到表单,但未触发验证(例如:未验证字段姓氏)。我必须触摸该字段,然后验证开始工作。

如何在patchValue 完成后立即触发验证。

请参考代码:https://stackblitz.com/edit/angular-wg5mxz?file=src/app/app.component.ts

欢迎提出任何建议。

【问题讨论】:

  • 补丁后可以调用this.form.updateValueAndValidity()
  • @MikeOne 不需要调用updateValueAndValidity(),pathValue方法自己调用。

标签: angular typescript validation angular-reactive-forms


【解决方案1】:

为了防止验证器在用户有机会编辑表单之前显示错误,您应该检查控件中的脏状态或触摸状态。

当用户更改观察字段中的值时,控件被标记为“脏”。 当用户模糊表单控件元素时,该控件被标记为“已触摸”。

你应该从你的*ngIf中删除lastNameControl.touched

查看https://angular.io/guide/form-validation了解更多信息

【讨论】:

    【解决方案2】:

    这只是因为您在@godocmat 提到的触摸lastName 或电子邮件时显示错误。如果您只是从 *ngIf 中删除 lastNameControl.touched 或 emailControl.touched,它就可以工作。 检查https://stackblitz.com/edit/angular-xced6b?file=src%2Fapp%2Fprofile-form%2Fprofile-form.component.html

    【讨论】:

      猜你喜欢
      • 2017-03-10
      • 2021-06-07
      • 1970-01-01
      • 2021-08-30
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 2020-03-30
      相关资源
      最近更新 更多