我正在使用角度为5的反应形式的验证器,并且难以设置基于另一个输入的值的验证器 .
表单看起来像这样:
let myRules = new FormArray([]);
myRules.push(this.newRuleFormGroup(1, 'period', 1));
this.myForm = new FormGroup({
'name': new FormControl(name, [Validators.required, this.validate_usedName.bind(this)]), // V: must not exist already
'icon': new FormControl(icon, [Validators.required]), // has default
'rules': myRules
})
'rules'是 FormArray
,我使用以下命令从模板中推送新的 FormGroup
:
newRuleFormGroup = (amount: number, period: string, repAmount: number = 1) => {
return new FormGroup({
'amount': new FormControl(amount, [Validators.required]),
'type': new FormControl(period, [Validators.required]),
'repAmount': new FormControl(repAmount, [this.validate_repAmount.bind(this)])
})
}
repAmount
仅在 type == "period"
时需要 . 在 repAmount
的验证器中,我试图达到父 FormGroup
并尝试获取其子 'type'
控件的值 . 像这样的东西:
validate_repAmount(control:FormControl): {[s:string]: boolean}{
let type = control.parent.get('type');// Cannot read property 'get' of undefined
let controlValue = control.value;
console.log(control.parent); // returns the parent FormGroup object
if(type.value == 'period' && (controlValue != '' || controlValue>0)) {
return {'repAmountMissing':true};
}
return null;
}
但我一直收到错误说 Cannot read property 'get' of undefined
. 如果我尝试 console.log(control.parent)
,我按预期获得FormGroup对象,但我似乎无法使用其属性以任何方式访问它 .
有人可以建议一种方法来访问验证器在同一组中的“类型”值吗?
2 回答
您应该将代码包装如下:
我曾经遇到过同样的问题,这就是我解决它的方法 .
Update: 你可以试试这样的东西 .
每当您想要进行一些交叉验证时,您应该将验证登录名移到祖先控件 . 在这种情况下,它将是你的
FormGroup
.Live demo