簡體   English   中英

將從 api 調用檢索到的參數傳遞給 FormBuilder 中的自定義驗證器

[英]Passing parameters retrieved from api call to Custom Validator in FormBuilder

在組件中,我將formBuilder用於Angular Reactive Forms

我從這篇文章中得到了示例代碼

min = 10;
max = 20;
ngOnInit() {
    this.loginForm = new FormGroup({
        email: new FormControl(null, [Validators.required]),
        password: new FormControl(null, [Validators.required, Validators.maxLength(8)]),
        age: new FormControl(null, [ageRangeValidator(this.min, this.max)])
    });
}

自定義驗證在 function ageRangeValidator中定義

function ageRangeValidator(min: number, max: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
        if (control.value !== undefined && (isNaN(control.value) || control.value < min || control.value > max)) {
            return { 'ageRange': true };
        }
        return null;
    };
}

萬一, minmax來自 api 調用。 如何將它們傳遞給 function 自定義驗證器?

FormControl API 提供setValidators方法。 您可以使用它來動態設置驗證器。 在 subscribe 回調中,您可以調用 setValidators ,如下所示:

嘗試這個:

 ..subscribe((result)=>{
    this.age.setValidators([ageRangeValidator(result.min,result.max)]);
    this.loginForm.get('age').updateValueAndValidity();    
  })

例子

我更喜歡 Chellappan 的答案,但是如果您要在應用程序 angular 的實時更改 max 和 min 的值,另一種方法是 function 驗證器屬於該組件並綁定到此

//this function IN the component
ageRangeValidator(): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value !== undefined && (isNaN(control.value) ||
          control.value < this.min ||control.value > this.max)
      ) {
        return { ageRange: true };
      }
      return null;
    };
  }

  //and when create the component
  age: new FormControl(15, [this.ageRangeValidator().bind(this)]) //<--see the bind(this)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM