从 Angular 的表单组中删除特定的验证器 [英] remove specific validator from the formgroup in Angular

查看:20
本文介绍了从 Angular 的表单组中删除特定的验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to remove the specific validator from validator array in order to set the controls again when some values changed.

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

I know normal solution where I need to set validators again and again.

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();
}

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

I would like to just removed the Validators.required on else part instead of setting validators again and again.

推荐答案

我认为最好的办法是使用customValidator";比如requireIf".

I think that the best bet is use a "customValidator" like "requireIf".

  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'))
})

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

But be carefull, when check change you need use

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

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

in the stackblitz I use mat-angular and use the (change) to make the updateValueAndValidity

UPDATE定义函数的typedef

UPDATE to defined the typedef of the function

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

这篇关于从 Angular 的表单组中删除特定的验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆