【发布时间】:2018-09-06 01:13:56
【问题描述】:
我正在构建一个反应式角度表单,我正在尝试找到一种方法来触发所有验证器提交。如果验证器是同步器,那没关系,因为我可以内联获取它的状态。否则,如果验证器是异步验证器并且尚未触发,则ngSubmit 方法上的表单将处于待处理状态。我尝试注册订阅表单statusChange 属性,但是当我使用markAsTouched 函数手动调用验证时它没有被触发。
这里有一些sn-ps:
//initialization of form and watching for statusChanges
ngOnInit() {
this.ctrlForm = new FormGroup({
'nome': new FormControl('', Validators.required),
'razao_social': new FormControl('', [], CustomValidators.uniqueName),
'cnpj': new FormControl('', CustomValidators.cnpj),
});
this.ctrlForm.statusChanges.subscribe(
x => console.log('Observer got a next value: ' + x),
err => console.error('Observer got an error: ' + err),
() => console.log('Observer got a complete notification')
)
}
//called on ngSubmit
register(ctrlForm: NgForm) {
Forms.validateAllFormFields(this.ctrlForm);
console.log(ctrlForm.pending);
//above will be true if the async validator
//CustomValidators.uniqueName was not called during form fill.
}
//iterates on controls and call markAsTouched for validation,
//which doesn't fire statusChanges
validateAllFormFields(formGroup: FormGroup) {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
} else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
}
关于如何确保异步验证器已执行,以便我可以继续使用所有验证器触发并完成的寄存器逻辑的任何想法?
【问题讨论】:
-
尝试使用 this.roleForm.get("razao_social").setAsyncValidators([CustomValidators.uniqueName]) 来分配验证器
-
为什么不创建一个返回可观察对象的 customValidator,并在注册时调用 CustomValidator(ctrlForm.value).subscribe(res=>{if (res.ok) continue else showError)?
-
@Eliseo,确实,它会解决问题,我没有想过这个,但我希望有一个更自动化的解决方案,我不需要知道 ngSubmit 上的验证器,使用 markAsTouched 或类似的
-
@Ricardo 我不明白它如何帮助我检索 register 方法的状态,如果你能给我一些想法......
-
@iangoop 一旦字段被修改,自定义验证器的想法就会被执行。如果你的验证器不工作是因为两个原因:错误的实现或错误的字段分配,我给出的解决方案您的分配错误,只需尝试测试至少该方法是否已被调用
标签: javascript angular angular-reactive-forms angular-validation