首页 > 解决方案 > 从 Angular 的表单组中删除特定的验证器

问题描述

我希望从验证器数组中删除特定的验证器,以便在某些值更改时再次设置控件。

我知道正常的解决方案,我需要一次又一次地设置验证器。

checked(event: MatCheckboxClickAction): void {
    const control = (this.form.get(
        'information',
    ) as FormGroup).controls.data1;
    if (event) {
        this.updateRequiredValidator(control);
    } else {
        control.setValidators([
            Validators.maxLength(9), Validators.minLength(2)
        ]);
        control.updateValueAndValidity();
    }
}

updateRequiredValidator(control: AbstractControl): void {
    control.setValidators([
        Validators.required,
        ...(control?.validator ? [control?.validator as ValidatorFn] : []),
    ]);
    control.updateValueAndValidity();
}

我想只删除 else 部分的 Validators.required 而不是一次又一次地设置验证器。

标签: javascriptangulartypescriptangular-reactive-forms

解决方案


我认为最好的选择是使用像“requireIf”这样的“customValidator”。

  requiredIf(field: string) {
    return (control: FormControl):{required:boolean}|null => {
      const form = control.parent as FormGroup;
      const check=form?form.get(field):null
      if (form && check && check.value)
        return !control.value ? { required: true } : null;

      return null;
    };
  }
//e.g.
this.form=new FormGroup({
   check:new FormControl();
   data1:new FormControl(null,this.requiredIf('check'))
})

但要小心,检查更改时需要使用

this.form.get('data1').updateValueAndValidity()

stackblitz我使用 mat-angular 并使用 (change) 来制作 updateValueAndValidity

更新定义函数的 typedef

requiredIf(field: string):ValidatorFn {
    return (control: AbstractControl):{required:boolean}|null => {
      ....
    }
}

推荐阅读