Angular 9反应形式:动态添加的验证器不显示错误消息

时间:2020-07-17 06:42:49

标签: angular validation angular-reactive-forms

我正在尝试根据条件将验证添加到我的一个表单字段中

this.formGroup = new FormBuilder().group({
      ....
      companyName: [''],
      ....
 });

以下是添加动态验证器的代码段

this.formGroup.get('personType').valueChanges.pipe(
      tap((personType: string) => {
       
        if (personType === '1') {
            this.formGroup.get('companyName').setValidators(Validators.required);
          } else {
            this.formGroup.get('companyName').clearValidators();
          }

          this.formGroup.get('companyName').updateValueAndValidity();
      })
    ).subscribe();

但是当我提交表格时,我面临两个问题:

  1. 即使我在companyName字段中输入了一个值,该值也没有显示在formgroup.value对象中(仍然是一个空字符串)

  2. 验证错误消息未显示,但我可以看到控件中设置了错误

     companyName: FormControl
         asyncValidator: null
         errors:
             required: true
         pristine:true
         touched:false
    

HTML

<form name="property" #formDirective="ngForm" class="form-example" [formGroup]="formGroup">
.....
<input  formControlName="companyName" />
....
</form>
          

2 个答案:

答案 0 :(得分:0)

动态验证:

dynamicValidation(): void {
    let control1 = null;
    control1 = this.formGroup.get('companyName');
      control1.setValidators([Validators.pattern(this.nameREGEX), Validators.minLength(this.minLength)]);
  control1.updateValueAndValidity();

  }

答案 1 :(得分:0)

在动态验证时遇到了同样的问题。我将用于提交表单的按钮更改为 type="submit" 或使用 (ngSubmit)="onFormSubmit()" 绑定。两者都有效。