问题
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