我正在构建一个反应式角形式,我正试图找到一种方法来触发提交时的所有验证器.如果验证者是同步的,那就没关系,因为我可以获得内联的状态.否则,如果验证器是异步验证器并且尚未触发,则ngSubmit方法上的表单将处于挂起状态.我已经尝试注册表单statusChange属性的订阅,但是当我使用markAsTouched函数调用验证时它没有被触发.
这是一些片段:
//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);
}
});
}
关于如何确保执行异步验证器的任何想法,以便我可以继续使用触发并完成所有验证器的寄存器逻辑?
解决方法:
在发出ngSubmit之前,Angular不会等待异步验证器完成.因此,如果验证器尚未解决,则表单可能无效.
使用Subject发出表单提交,您可以将map切换到form.statusChange并过滤结果.
从startWith开始确保没有悬挂发射,如果表单在提交时有效.
通过PENDING过滤等待此状态更改,并且(1)确保在挂起后的第一次发射时完成流:VALID或INVALID.
//
// <form (ngSubmit)="formSubmitSubject$.next()">
this.formSubmitSubject$= new Subject();
this.formSubmitSubject$
.pipe(
tap(() => this.form.markAsDirty()),
switchMap(() =>
this.form.statusChanges.pipe(
startWith(this.form.status),
filter(status => status !== 'PENDING'),
take(1)
)
),
filter(status => status === 'VALID')
)
.subscribe(validationSuccessful => this.submitForm());
您还可以添加一个触发器,触发将窗体设置为脏的副作用.
原文地址:https://codeday.me/bug/20190607/1194932.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。