Lax*_*nge 2 typescript angular angular-reactive-forms angular-forms
我有一个几乎没有控件的表单组,仅当至少一个字段具有值时才需要所有字段。即,任一用户都可以将所有字段保留为空或在所有字段中输入数据。每个控件都需要经过验证才能在其下方显示所需的错误。
我尝试在内置所需验证器的帮助下为此构建自定义验证器,但它仅验证当前控制。
allFieldRequired(ctrlName: string): ValidatorFn {
return (ctrl: AbstractControl) => {
if (!ctrl.parent || !Object.values(ctrl.parent.value).join('')) {
return null;
}
return CustomValidators.required()(ctrl)
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的实现。
小智 5
为什么不简单地
this.myForm.get('myFirstControl').valueChanges.subscribe(value => {
for (const control of this.myForm.controls) {
if (!value) { control.setValidators([]); }
else { control.setValidators([Validators.required]); }
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2536 次 |
| 最近记录: |