简体   繁体   English

Angular 表单在使用 ng-zorro 初始化时未显示错误

[英]Angular form not showing error on init with ng-zorro

I have an angular application with reactive forms.我有一个带有反应性 forms 的 angular 应用程序。 I use ng-zorro as UI framework.我使用 ng-zorro 作为 UI 框架。 There is a case that client could open a form, which became invalid during his workflow in the app.有一种情况是客户可以打开一个表单,该表单在他的应用程序工作流程中变得无效。

The problem their is that angular marks the form as invalid, but no error messages displayed from ng-zorro until the form control is touched.他们的问题是 angular 将表单标记为无效,但在触摸表单控件之前不会从 ng-zorro 显示错误消息。

function validateEmail(c: FormControl) {
  const URL_REGEX = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;

  return URL_REGEX.test(c.value) ? null : {
    validateEmail: true
  };
}

      <nz-form-item>
        <nz-form-label
          nzXXl="3"
          nzXl="4"
          nzLg="6"
          nzMd="7"
          nzSm="10"
          nzXs="24"
          nzFor="videoLink"
          nzRequired>
          Video Link
        </nz-form-label>
        <nz-form-control
          nzXXl="21"
          nzXl="20"
          nzLg="18"
          nzMd="17"
          nzSm="14"
          nzXs="24"
          nzHasFeedback
          [nzErrorTip]="videoErrorTpl"
        >
          <input nz-input formControlName="videoLink" maxlength="150"/>
          <ng-template #videoErrorTpl let-control>
              <ng-container *ngIf="control.hasError('required')">
               required
              </ng-container>
              <ng-container *ngIf="control.hasError('validateEmail')">
                Please enter a valid URL
              </ng-container>
            </ng-template>
        </nz-form-control>
      </nz-form-item>

If I understood the problem correctly, the root of it is that all fields are marked as pristine.如果我正确理解了这个问题,那么问题的根源就是所有字段都被标记为原始。 If you need to display errors immediately after starting the form component, try to set the status for all fields to dirty.如果您需要在启动表单组件后立即显示错误,请尝试将所有字段的状态设置为脏。 For example:例如:

ngOnInit(): void {
  for (const key in this.validateForm.controls) {
    this.validateForm.controls[key].markAsDirty();
    this.validateForm.controls[key].updateValueAndValidity();
  }
} 

where validateForm is a model of form其中 validateForm 是 model 形式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM