【发布时间】:2020-05-25 13:11:48
【问题描述】:
我正在尝试在 Angular 中向我的表单添加一些自定义验证。问题是当我在表单中只有一个 AsyncValidator 时,一切都按预期工作,所以我更改了一个值,表单状态更改为 Valid。而当我有两个 AsyncValidator 时,表单会保持在 Pending 状态,直到我同时更改它们。
这是我的代码:
uniqueValue.validator.ts
export function UniqueValidator(service: ExistsService, originalValue: string = null): AsyncValidatorFn {
return control => {
if (control.valueChanges == null) {
return of(null);
}
return control.valueChanges
.pipe(
debounceTime(400),
distinctUntilChanged(),
switchMap(value => {
if (value === originalValue) {
control.markAsPristine();
return of(false);
}
return service.exists(value);
}),
map((unique: boolean) => (!unique ? null : { 'notUnique': true })),
first());
}
}
some-component.component.ts
ngOnInit() {
this.form= this.fb.group({
email: [this.email,
[Validators.required],
UniqueValidator(this.myService)
],
username: [this.userName,
[Validators.required],
UniqueValidator(this.myService)
],
fullName: [this.fullName]
});
this.form.markAsPristine();
}
submitButtonEnabled(): boolean {
return this.form.valid
&& this.form.dirty;
}
附言这是一个Edit Form,因此所有字段的初始状态始终存在值。因此,当表单第一次加载时,两个字段(电子邮件和用户名)都是有效的,并且其中一个字段发生更改,它将触发 AsyncValidator,如果响应为 true,submitButtonEnabled 应该返回 true。
【问题讨论】:
标签: angular angular-forms