从Angular的表单组中删除特定的验证器 [英] remove specific validator from the formgroup in 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,而不是一遍又一遍地设置验证器.
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 to defined the typedef of the function
requiredIf(field: string):ValidatorFn {
return (control: AbstractControl):{required:boolean}|null => {
....
}
}
这篇关于从Angular的表单组中删除特定的验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!