首页 > 解决方案 > FormGroup.controls 在自定义验证器中未定义

问题描述

我有一个带有 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。

这发生在我打开页面时。

标签: angularformbuildercustomvalidator

解决方案


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


推荐阅读