繁体   English   中英

未在 angular 9 反应形式中设置动态验证

[英]not set dynamic validation in angular 9 reactive form

我有形式,我用 angular 9 中的反应形式创建它。

在这种形式中,我有一个切换,当此切换为true时,字段moreAccountInfo必须具有验证要求,而当未选择切换时,该字段必须是不需要的。

这是我的表格:

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]
})

}

这是 function 用于创建动态验证:

   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;
  }

当用户点击切换时,这个 function 被设置:

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

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

angular 5 根据另一个字段的值有条件地验证字段

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();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM