提问人:Kpo 提问时间:9/5/2023 更新时间:9/5/2023 访问量:47
Angular FormControl updateOn blur 异步验证器获取旧值
Angular FormControl updateOn blur async validator gets old value
问:
我为 angular 表单创建了一个自定义验证器,其目的是检查输入中输入的文本是否尚未使用
export class CustomValidators {
static titleNotExists(myService: MyService, category: string): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return myService
.checkTitleAvailability(category, control.value)
.pipe(
map((isAvailable: boolean) =>
isAvailable || control.pristine ? null : { titleExists: `An object with this title already exists for category ${category}.` }
)
);
};
}
}
我希望这个验证器只在 onBlur 上运行,这样我就不会对输入的每个字符发出请求,所以为此我将 updateOn 设置为“blur”
export class MyModalComponent implements OnInit {
@Input category: string;
myForm: FormGroup = this._formBuilder.group({
title: ['', { validators: [Validators.pattern(/^(\w|[&-. ])*$/), Validators.maxLength(100), Validators.required], updateOn: 'blur' }]
});
get titleFormControl(): FormControl {
return <FormControl>this.myForm.get('title');
}
constructor(private _myService: MyService, private _formBuilder: FormBuilder) {}
ngOnInit(): void {
this.titleFormControl.setAsyncValidators([CustomValidators.titleNotExists(this._myService, category)]);
}
}
<form (ngSubmit)="save.focus()" [formGroup]="myForm">
<input
[formControl]="titleFormControl"
[isRequired]="true"
[label]="'Title'"
>
<button
#save
(click)="save()"
[disabled]="!myForm.valid"
aria-label="submit"
color="primary"
mat-raised-button
>
SAVE
</button>
</form>
但是当我在输入中输入值时,我可以在我的请求中看到发送要检查的值永远不会更新(如果输入为空,则始终为空,如果有初始值),我不明白为什么会发生这种情况...... 如果我将 updateOn 保留为默认的 onChange,它确实可以正常工作,对每个字符发出请求并正确返回它是否可用......
答: 暂无答案
评论