Angular Forms 响应式(Reactive) - 交叉控制验证

标签 angular angular-forms custom-validators

我正在为 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/

相关文章:

validation - 如何在自定义验证方法中使用现有的 Rails 验证器?

angular - 在 angular2 中呈现编辑表单。我如何等待来自服务的数据?

Angular 4 从复选框中获取值

Angular 2根据掩码验证输入

Angular 表单,如何在表单提交成功后自动滚动到顶部?

asp.net - 如何将 javascript 连接到 .Net 中的 CustomValidator 控件

javascript - 在 Angular 中如何根据数字条件编写字符串

javascript - 如何将 p-checkbox 设置为选中并将选择对象存储到列表

javascript - FormGroup 中的 Angular 2/4 FormControl 无法在带有标签的表单上显示

validation - Angular 2 : how to apply two or more validators to the same control?