我正在使用最新的 angular 版本之一,我正在尝试创建一个自定义验证来验证代码,认为是 RestAPI,下面的示例工作正常,但 它不适用于按键事件 ,它仅适用于 onblur 事件。 只有当输入字段失去焦点时,才会出现“代码不可用”文本。你有什么想法吗?
提前感谢您的帮助!
这是表单生成器
this.form = this.formBuilder.group({
code: ['',
[Validators.required, Validators.pattern('^[A-Za-z0-9]{4}')],
this.asyncCodeValidator.validate(),
]
});
这是 asyncCodeValidator 服务
@Injectable({ providedIn: 'root' })
export class AsyncCodeValidatorService {
constructor(private codeService: CampaignService) {}
validate(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
return this.searchCode(control.value).pipe(
map(result => {
return result.available ? null : { notUnique: 'Action code not unique' };
})
);
};
}
searcCode(code: string): Observable<CodeValidate> {
return timer(500).pipe(
switchMap(() => {
return this.codeService.validateCode(code); // return Observable<CodeValidate>
})
);
}
}
这是html控件
<form [formGroup]="form">
<input type="text" formControlName="code">
<p style="color: red" *ngIf="form.get('code').errors?.notUnique">code not available</p>
</form>
使用
"@angular/common": "11.2.12",
"@angular/compiler": "11.2.12",
"@angular/core": "11.2.12",
"@angular/forms": "11.2.12",
"@angular/material": "11.2.12",
答案 0 :(得分:0)
我找到了错误出在组件的changeStrategy.OnPush上的解决方案