gpt4 book ai didi

Angular 7 : Async validator change detection

转载 作者:行者123 更新时间:2023-12-02 16:49:49 31 4
gpt4 key购买 nike

我编写了一个异步验证器来检查输入的电子邮件是否已存在于我的数据库中。

我使用响应式(Reactive)表单 API 来构建我的表单,并且我已将异步验证器配置为仅在“模糊”时触发。正如 angular documentation 中提到的

效果很好:当我离开字段时会触发验证,但直到我与表单交互时才会显示错误消息。

如果我在验证中使用 setTimeout 函数手动触发changeDetection,它就会起作用。

知道为什么验证完成后不直接显示此错误吗?

这是我的表单定义:

private initPersonalInformationFormGroup() {
this.personalInformationFormGroup = this._formBuilder.group({
lastName: ['', Validators.required],
firstName: ['', Validators.required],
gender: [Gender.MALE],
birthDate: [''],
birthPlace: [''],
nationality: [''],
inss: ['', [Validators.minLength(11), Validators.maxLength(11), Validators.pattern('[0-9]{11}')]],
email: ['', {
validators: [Validators.required, Validators.email],
asyncValidators: [this._studentEmailValidator()],
updateOn: 'blur'
}],
phoneNumber: [null, Validators.pattern('\\+32[1-9][0-9]{7,8}')],
address: this._formBuilder.group({
street: ['', [Validators.maxLength(60)]],
houseNumber: ['', [Validators.maxLength(10)]],
city: ['', [Validators.maxLength(60)]],
postalCode: [null, [Validators.min(1000), Validators.max(9999)]],
}, {
validators: this._completeAddressValidator()
}),
previousSchool: ['', Validators.maxLength(60)],
additionalInformation: ['']
})
}

我的验证方法:

private _studentEmailValidator(): AsyncValidatorFn {
return (control: FormGroup): Observable<{ [key: string]: any } | null> => {
const email = control.value;
// setTimeout(() => this._checkDetectorRef.detectChanges(), 5000);
return this._adminFacade.checkStudentWithEmailExists(email).pipe(
take(1),
map(exists => exists ? {'emailAlreadyUserByStudent': {value: email}} : null),
catchError(() => null)
);
}
};

以及模板的部分:

<mat-form-field fxFlex="60">
<mat-placeholder>
<mat-icon>email</mat-icon>
<span> Email</span>
</mat-placeholder>
<input matInput formControlName="email">
<mat-error *ngIf="email.hasError('emailAlreadyUserByStudent')">
Email déjà utilisé.
</mat-error>
<span *ngIf="email.pending">Validating...</span>
</mat-form-field>

最佳答案

作为一种解决方法(我仍然不确定这是最好的方法,因为在代码示例中没有必要......),我在验证器函数的末尾添加了一个手动 detectorChanges :

  private _studentEmailValidator(): AsyncValidatorFn {
return (control: FormGroup): Observable<{ [key: string]: any } | null> => {
const email = control.value;
return this._adminFacade.checkStudentWithEmailExists(email).pipe(
take(1),
map(exists => exists ? {'emailAlreadyUserByStudent': {value: email}} : null),
catchError(() => null),
tap(() => setTimeout(() => this._checkDetectorRef.detectChanges(), 0))
);
}

};

关于 Angular 7 : Async validator change detection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55103202/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com