【发布时间】:2021-08-14 13:03:24
【问题描述】:
我有表单数组,必须根据一个变量来控制,现在我编写了如下的自定义验证器
recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (!control.value) {
return null;
}
if (this.myVariable === 'constant1') {
return Validators.required;
}
return null;
};
}
现在这将检查 'myVariable' 的值并输入 required 但不知何故它不起作用,我正在添加这个自定义验证器,如下所示
const fbGroup = this.fb.group({
recurringControl1: this.fb.control('', [this.recurringValidator()]),
recurringControl2: this.fb.control('', [this.recurringValidator()]),
recurringControl3: this.fb.control('', [this.recurringValidator()])
});
this.myForm = this.fb.group({
control1: fb.control('', [this.recurringValidator()]),
groupcontrol1: fb.array([])
});
当我点击提交时,即使 myVariable 的值是 'constant1' ,表单也是有效的。
请有任何建议或修改。
这里是 stackblitz 链接 https://stackblitz.com/edit/angular-form-array-validators?
【问题讨论】:
-
您从异步验证器函数返回
Validators.requred的任何特殊原因? @Shaswata -
取决于变量值,也可以不要求,
标签: angular typescript angular-forms