基于父formValues需要的角度6设置验证器

时间:2018-10-22 12:05:19

标签: angular validation conditional-statements

我有一个嵌套的formGroup,想基于父值设置一个验证器(必需)。

this.userForm = fb.group({
  audio: [''],
  audioSet: fb.group({
    producer: [0, this.userForm.get('audio').value ? Validators.required : '']
  }),
})

但是这次this.userForm.get('audio').value抛出未定义的(正常)。

DetailsComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'get' of undefined
at new DetailsComponent (details.component.ts:24)
at createClass (core.js:9303)
at createDirectiveInstance (core.js:9186)
at createViewNodes (core.js:10406)
at createRootView (core.js:10320)
at callWithDebugContext (core.js:11351)
at Object.debugCreateRootView [as createRootView] (core.js:10838)
at ComponentFactory_.push../node_modules/@angular/core/fesm5/core.js.ComponentFactory_.create (core.js:8666)
at ComponentFactoryBoundToModule.push../node_modules/@angular/core/fesm5/core.js.ComponentFactoryBoundToModule.create (core.js:3315)
at ViewContainerRef_.push../node_modules/@angular/core/fesm5/core.js.ViewContainerRef_.createComponent (core.js:8776)

所以我将验证器设置为valueChange:

    this.userForm.controls['audio'].valueChanges.subscribe(result => {
  const ctrl = this.userForm.get(['audioSet', 'producer']);
  if (result) {
    ctrl.setValidators(Validators.required);
    ctrl.updateValueAndValidity();
  } else {
    ctrl.setValidators(null);
    ctrl.updateValueAndValidity();
  }
});

我的嵌套formGroup中有很多值, 是实现这一目标的更好的方法还是新的方法?

1 个答案:

答案 0 :(得分:1)

  

您应该将get称为Function,但您将get视为Array

更改

this.userForm.get['audio'].value

this.userForm.get('audio').value