没有以角度9反应形式设置动态验证

时间:2020-06-08 05:56:26

标签: javascript angular typescript

我有形式,我用角9的反应形式来制造它。

以这种形式,我有一个切换,当该切换为true时,字段moreAccountInfo必须具有验证要求,而当未选中时,切换thet字段必须为not requeire。

这是我的表格:

InitialFrom(): void {
  this.addElectricMoneyFG = this.fromBuilder.group({
   hasParent: [false],
   parentId: [null],
   name: ['', Validators.required],
   code: ['', Validators.compose([Validators.required])],
   type: ['', Validators.compose([Validators.required])],
   hasAccountInfo: [false],
   moreAccountInfo: [null],
   description: ['', Validators.compose([Validators.required])],
   published: [false]
})

}

这是用于创建动态验证的功能:

   SetValidationMoreInfoValidation(): void {

    this.addElectricMoneyFG.get('moreAccountInfo').setValidators(this.f.hasAccountInfo.value === true ? [Validators.required] : null);
    this.addElectricMoneyFG.get('moreAccountInfo').updateValueAndValidity();

    this.showMoreInfo = this.f.hasAccountInfo.value;
  }

,当用户单击切换按钮时,将设置此功能:

     <mat-slide-toggle
      color="primary"
      formControlName="hasAccountInfo"
      (change)="SetValidationMoreInfoValidation()"
    >
    SetToggle /mat-slide-toggle
    >

但它不起作用。需要moreAccountInfo。有什么问题 ?

1 个答案:

答案 0 :(得分:0)

angular 5 conditionally validate field based on another field's value

const control1 = <FormControl>this.form.get('control1');
const control2 = <FormControl>this.form.get('control2');

control1.valueChanges.subscribe(value => {
  if (value === 'first-condition') {
    control2.setValidators([Validators.required, ...])
  }
  else {
    control2.setValidators(null);
  }

  control2.updateValueAndValidity();
});