我正在为 Angular 5 中的响应式(Reactive)表单开发验证器,但在设置基于另一个输入值的验证器时遇到了困难。
表单看起来像这样:
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;
}
但我不断收到一条错误消息:无法读取未定义的属性“get”
。如果我尝试 console.log(control.parent)
,我会按预期获得 FormGroup 对象,但我似乎无法使用其属性以任何方式访问它。
谁能建议一种方法来为验证器访问同一组中的“类型”值?
最佳答案
你应该像下面这样包装你的代码:
if (parent) { YOUR_VALIDATION_GOES_HERE }
我曾经遇到过同样的问题,这就是我解决它的方法。
更新:您可以尝试这样的操作。
validate_repAmount(control: FormControl): { [s: string]: boolean } {
const parent = control.parent;
if (parent) {
let type = parent.get('type');
let controlValue = control.value;
if (type.value == 'period' && (controlValue != '' || controlValue > 0)) {
return { 'repAmountMissing': true };
}
}
return null;
}
关于Angular Forms 响应式(Reactive) - 交叉控制验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49980153/