【问题标题】:FormGroup.controls is undefined in the custom validatorFormGroup.controls 在自定义验证器中未定义
【发布时间】:2019-08-13 20:50:06
【问题描述】:

我有一个带有 html 页面的 Ionic 项目。该页面具有以下形式:

<form [formGroup]="configureLeagueForm">
  <ion-item>
    <ion-label  position="floating">TEXT</ion-label>
    <ion-input type="number" formControlName="roundsQuantity" ></ion-input>
  </ion-item>
  <ion-item *ngIf="!configureLeagueForm.controls.roundsQuantity.valid  && (configureLeagueForm.controls.roundsQuantity.dirty || submitAttempt)">
      <p [class.invalid]="!configureLeagueForm.controls.roundsQuantity.valid  && (configureLeagueForm.controls.roundsQuantity.dirty || submitAttempt)" >TEXT IF ERROR .</p>
  </ion-item>
</form>

还有 .ts 文件

this.configureLeagueForm = this.formBuilder.group({
  roundsQuantity: [1, Validators.compose([Validators.min(1), Validators.max(100), ConfigureChampionshipFormValidator.roundsQuantity])],
});

现在,我的验证者

export class ConfigureChampionshipFormValidator {

static roundsQuantity(group: FormGroup) : any{

var roundsQuantity = group.controls['roundsQuantity'].value;

if(String(roundsQuantity).trim() == ""){ // Just an example of validation

  group.controls['roundsQuantity'].setErrors({"mandatory_error": true});
  return { "mandatory_error": true };      
} else{
  return { "mandatory_error": false }; 
}
}

}

但在代码的这一步:

group.controls['roundsQuantity'].value

我有未定义的 group.controls。

这发生在我打开页面时。

【问题讨论】:

    标签: angular formbuilder customvalidator


    【解决方案1】:

    您的验证器设置在 FormControl (roundsQuantity) 上。因此,它将作为参数接收的是表单控件。不是它的父表单组。

    【讨论】:

      【解决方案2】:

      您有一些问题,就像其他答案中提到的那样,您的自定义验证器正在接收表单控件,而不是整个组。

      其次,如果值通过验证,您的自定义验证器应返回 nullnull 在验证器中被认为是有效的。因此,将您的自定义验证器更改为:

      export class ConfigureChampionshipFormValidator {
        static roundsQuantity(roundsQuantity: AbstractControl): any {
          if (!roundsQuantity.value) {
            return { "mandatory_error": true };
          } 
          return null;
        }
      }
      

      Pure Angular DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-04
        • 2013-11-15
        • 1970-01-01
        相关资源
        最近更新 更多