Angular- react 形式 : How to validate fields after patchValue

标签 angular typescript validation angular-reactive-forms

我有一个使用 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

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

最佳答案

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了解更多信息

关于Angular- react 形式 : How to validate fields after patchValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67281326/

相关文章:

angular - 从指令中创建/获取 TemplateRef

javascript - Vue.js 变量变为未定义

javascript - Angular 2 - Kendo UI 下拉列表默认值

css - 侧面菜单 Angular 4 中的动画背景颜色

node.js - Firebase部署找不到serviceAccountKey

java - 如何验证 HTML 是否符合 W3C 标准

jquery - 如何使用 jQuery 重载 focusOut?

validation - 报表参数验证

javascript - 使用 http 拦截器从 ionic 存储设置默认请求 header - Angular 5 - Ionic 3

angular - 在 APP_INITIALIZE 之后初始化其他提供者