Angular- 响应式表单:如何在 patchValue 之后验证字段

Angular- Reactive Forms: How to validate fields after patchValue

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

简介-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"
      });
    ...
  }

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

如有任何建议,我们将不胜感激。

To prevent the validator from displaying errors before the user has a chance to edit the form, you should check for either the dirty or touched states in a control.

When the user changes the value in the watched field, the control is marked as "dirty". When the user blurs the form control element, the control is marked as "touched".

您应该从 *ngIf

中删除 lastNameControl.touched

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

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