【发布时间】:2021-10-16 18:19:10
【问题描述】:
我有一个响应式表单并添加了一个自定义异步验证器,以通过检查可用值数组来检查输入的值是否唯一。正在调用验证器,但验证错误“重复”未添加到表单字段错误中,并且未显示在模板中。不知道我在这里做错了什么。
component.ts
private registerFormGroup(): void {
this.titleField = new FormControl(
{ value: this.auditTemplate.title, disabled: true },
[Validators.required],
[TemplateNameValidator.createValidator(this.auditTemplateService)]
);
this.templateForm = this.formBuilder.group({
title: this.titleField,
tags: [this.auditTemplate.tags]
});
}
名称验证器:
export class TemplateNameValidator {
static createValidator(auditTemplateService: AuditTemplateService): AsyncValidatorFn {
console.log("Static factory call");
return (control: AbstractControl): Observable<ValidationErrors | null> => {
if(isEmptyInputValue(control.value)) {
return of(null);
} else {
return control.valueChanges.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap((name: string) =>
auditTemplateService.isNameUnique(name)
.pipe
(
tap(response => console.log('inside switchmap', response)),
map(isUnique => !isUnique ? { 'duplicate' : true } : null),
catchError(() => of(null))
)
)
);
}
};
}
}
function isEmptyInputValue(value: any): boolean {
return value === null || value.length === 0;
}
在模板 html 中,如果我尝试显示错误,它不会显示任何内容:
<span>Duplicate: </span>{{templateNameField.errors?.duplicate}}<br>
谢谢
【问题讨论】:
标签: rxjs angular-reactive-forms angular11