【问题标题】:remove specific validator from the formgroup in Angular从 Angular 的表单组中删除特定的验证器
【发布时间】:2021-03-08 18:11:47
【问题描述】:

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

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

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,而不是一次又一次地设置验证器。

【问题讨论】:

    标签: javascript angular typescript angular-reactive-forms


    【解决方案1】:

    您可以创建自定义验证器函数,而不是添加和删除验证器,该函数可以检查所有可能的错误并使用AbscractControlsetError 方法设置错误

    【讨论】:

    • 但我需要根据检查条件删除validators.required
    • 你可以将自定义验证器放在 FormGroup 上它自己
    【解决方案2】:

    我认为最好的办法是使用像“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()
    

    the stackblitz我使用mat-angular并使用(更改)来进行updateValueAndValidity

    UPDATE来定义函数的typedef

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

    【讨论】:

    • 只是一个小问题。它如何适用于嵌套组?
    • form = new FormGroup({ check: new FormControl(true), val: new FormGroup({ check: new FormControl(true), }), data1: new FormControl(null, [ this.requiredIf ("val.check"), Validators.maxLength(10) ]) });
    • Type '(control: FormControl) => { required: boolean;} | null' 不可分配给类型 'ValidatorFn'。参数“控制”和“控制”的类型不兼容。我确实在 stackblitz 中遇到了以下错误。
    • app,如果在嵌套组中,您需要“获取”表单,则应使用 parent.parent,例如如果您的表单组是{form:{check,{some:data1}},并且您可以使用获取点符号,例如form('subgroup.check')。如果您的验证器出现错误,请使用 AbstractControl 而不是 FormControl
    • 逻辑是一样的,都需要“get”两个checkbox(先找到formgroup,再用get()找到两个checkbox)
    猜你喜欢
    • 2020-04-27
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2022-07-26
    • 2022-12-22
    相关资源
    最近更新 更多