remove specific validator from the formgroup in Angular

落花浮王杯 提交于 2021-01-28 08:32:22

问题


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

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


回答1:


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

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

UPDATE to defined the typedef of the function

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



回答2:


Instead of adding and removing the validators, you can create the custom validator function that can check all possible error and set error using setError method of AbscractControl



来源:https://stackoverflow.com/questions/65012294/remove-specific-validator-from-the-formgroup-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!