如果FormControl错误,则不会调用FormGroup异步验证器 [英] FormGroup async validator not called if FormControl is in error
问题描述
我已经为特定字段编写了一个异步验证器,为2个字段编写了一个异步验证器:
I've wrote an async validator for a specific field an another one for 2 fields of the form:
this.aliasCtrl = formBuilder.control('', [], [
(control: AbstractControl) => {
return new Promise(resolve => {
if(control.value === 'aaa') {
resolve({error: true});
} else {
resolve(null);
}
});
}
]);
this.formGroup = formBuilder.group({
firstName: formBuilder.control('', []),
lastName: formBuilder.control('', []),
alias: this.aliasCtrl
}, {
asyncValidator: (group: FormGroup) => {
return new Promise(resolve => {
if(group.value.firstName === 'aaa' && group.value.lastName === 'aaa') {
resolve({error2: true});
} else {
resolve(null);
}
});
}
});
它们两个都正常工作.关键是,当别名控件验证器抛出错误时(当字段包含aaa
时),全局"将永远不会出错.
Both of them are working correctly. The point is, when the alias control validator throws an error (when the field contains aaa
), the "global" one never does.
我的问题的帮手: http://plnkr.co/edit/vyr48ke7fWEUwrXy43tn?p =预览
如何复制:
-
从第一个字段开始,在所有字段中输入
-
aaa
.很好,一切正常. - 重新装上弹子. 从最后一个字段开始,在所有字段中
- 放入
aaa
.编辑lastName
字段的firstName
时,不会调用全局"验证器(我在插件中添加了一些console.log
,以查看何时调用验证器).
- put
aaa
in all fields starting with the first one. Good, everything works. - Reload the plunker.
- put
aaa
in all fields starting with the last one. The "global" validator is not called when editingfirstName
oflastName
field (I've added someconsole.log
in the plunker to watch when validators are called).
该行为是故意的吗?为什么?如果错误已经存在,如何调用全局"验证器事件?
Is the behaviour intentional? Why? How to call the "global" validator event if an error already exists?
推荐答案
回答我的问题的一种方法是定义一个包含字段firstName
和lastName
的formGroup
.这是解决方案的解决方案: http://plnkr.co/edit/HAmaYySbxVE15VOl9uJ4?p=preview
One way to answer my question is to define a formGroup
containing fields firstName
and lastName
. Here's a plunker with the solution: http://plnkr.co/edit/HAmaYySbxVE15VOl9uJ4?p=preview
作为参考,我在这里输入我的formGroup
:
For reference, I let here my formGroup
:
this.aliasCtrl = formBuilder.control('', [], [(control: AbstractControl) => {
return new Promise(resolve => {
if(control.value === 'aaa') {
resolve({error: true});
} else {
resolve(null);
}
});
}
]);
this.nameGroup = formBuilder.group({
firstName: formBuilder.control('', []),
lastName: formBuilder.control('', [])
}, {
asyncValidator: (group: FormGroup) => {
return new Promise(resolve => {
if(group.value.firstName === 'aaa' && group.value.lastName === 'aaa') {
resolve({error2: true});
} else {
resolve(null);
}
});
}
});
this.formGroup = formBuilder.group({
name: this.nameGroup,
alias: this.aliasCtrl
});
这篇关于如果FormControl错误,则不会调用FormGroup异步验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!