[英]Angular FormControl with async validator stays in pending status
當我添加沒有同步驗證器的異步驗證器時,我的表單無法正常工作。
當我將異步驗證器與同步驗證器一起添加時,表單有效
name: new FormControl(
'',
Validators.required,
this.validate.bind(this)
),
但是當我刪除同步驗證器時,表單不再起作用,即其他必需的控件沒有觸發
name: new FormControl(
'',
null,
this.validate.bind(this)
),
這是驗證 fn
private validate(control:AbstractControl):Observable<ValidationErrors> {
return control.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap((value: boolean) => {
//some logic
return of(null);
}
請不要像某些帖子中建議的那樣使用 first() 和 take(1) 不起作用。 當我在同步驗證器上添加 Validator.required 時,一切正常
遵循此線程https://github.com/angular/angular/issues/13200后,我能夠解決此問題
解決方案包括當控件是 prestine 或沒有 valueChanges 時返回 null observable,使用 take(1) 確保 validate() fn 中返回的 observable 是有限的。
private validate(control:AbstractControl):Observable<ValidationErrors> {
if (!control.valueChanges || control.pristine) {
return of(null);
} else {
return control.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
take(1),
switchMap((value: boolean) => {
//some logic
return of(null);
},
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.