javascript - 从 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 而不是一次又一次地设置验证器。
解决方案
我认为最好的选择是使用像“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()
在stackblitz我使用 mat-angular 并使用 (change) 来制作 updateValueAndValidity
更新定义函数的 typedef
requiredIf(field: string):ValidatorFn {
return (control: AbstractControl):{required:boolean}|null => {
....
}
}
推荐阅读
- c# - 如何将 Home/End 按钮按下传播到 WPF ScrollViewer 内的 UWP RichEditBox?
- matlab - 向量中的数据排列
- python - 在 while 循环 discord.py 之后执行 if 语句
- vue.js - Vue2Leaflet 没有在地图中放置自定义图标
- .net - 如果所有迁移都被意外删除了怎么办?
- r - 我可以在一个轴上证明和斜体不同类别吗?
- javascript - 如何使用按钮在 html 中显示 js 对象
- react-native - Branch.io(React-Native) :: 没有在 Mixpanel LiveView 上获得 CLICK 分支事件
- firebase - 基于子集合的 Firestore 规则
- java - 如何为具有很少依赖关系的服务层编写集成测试