【发布时间】:2019-12-02 09:09:35
【问题描述】:
我在我的 Angular7 应用程序中使用带有 updatOn: 'blur' 的表单异步验证。
stackblitz
在这种情况下,我需要检查名称是否唯一(异步验证)。
this.myForm.get('name').statusChanges.subscribe(status => {
if (status === 'VALID') {
// to save the name to database.
} else {
// to show some errors.
}
});
问题是,这段代码放在哪里?
当前方式
我在子组件中试过这个
@Input()
set myForm(myForm: FormGroup) {
this._myForm = myForm;
this.myForm.get('name').statusChanges.subscribe(status => { // to subscribe statusChanges here.
if (status === 'VALID') {
// to save the name to database.
} else {
// to show some errors.
}
});
}
get myForm() {
return this._myForm;
}
_myForm: FormGroup
成功了。但是我至少有 10 个属性要做表单验证,这会给这个@Input() set myForm() {} 添加太多代码,所以我需要在另一个函数中执行此操作。
所以,我退出订阅@Input 属性中的statusChange。如果不在这里,我应该在哪里做呢?
我无法订阅ngOnInit 中的statusChange,因为ngOnInit 中的值未定义。
请大家帮帮我。
【问题讨论】:
-
@MoxxiManagarm 是的,但我仍然需要验证结果来决定下一步应该做什么。
标签: angular forms angular2-form-validation