从 Angular 中的表单组中删除特定验证器
remove specific validator from the formgroup in Angular
我希望从验证器数组中删除特定的验证器,以便在某些值更改时再次设置控件。
我知道正常的解决方案,我需要一次又一次地设置验证器。
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,而不是一次又一次地设置验证器。
您可以创建自定义验证器函数来检查所有可能的错误并使用 AbscractControl
的 setError
方法设置错误,而不是添加和删除验证器
我认为最好的办法是使用像“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 并使用 (change) 使 updateValueAndValidity
UPDATE 定义函数的类型定义
requiredIf(field: string):ValidatorFn {
return (control: AbstractControl):{required:boolean}|null => {
....
}
}
我希望从验证器数组中删除特定的验证器,以便在某些值更改时再次设置控件。
我知道正常的解决方案,我需要一次又一次地设置验证器。
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,而不是一次又一次地设置验证器。
您可以创建自定义验证器函数来检查所有可能的错误并使用 AbscractControl
setError
方法设置错误,而不是添加和删除验证器
我认为最好的办法是使用像“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 并使用 (change) 使 updateValueAndValidity
UPDATE 定义函数的类型定义
requiredIf(field: string):ValidatorFn {
return (control: AbstractControl):{required:boolean}|null => {
....
}
}