如何使用ngx格式执行与debounce异步验证?



我在我的表单配置中尝试了以下操作:

fields: FormlyFieldConfig[] = [
{
key: 'text',
type: 'input',
modelOptions: {
debounce: {
default: 2000,
},
},
templateOptions: {
label: 'Debounce',
},
validators: ["test"]
},
];

和以下FormlyConfig定义:

{
validationMessages: [
{
name: 'test',
message: "The value cannot be X",
},
],
validators: [
{
name: "test",
validation: ((control: FormControl) => {
return !!control.value || control.value === "X" ? null :  {test: true};
})
}
]
}

我观察到的是,验证器是立即运行的,而不管指定的debounce。

此外,模型更新为debounce,而角形立即更新。

这是一个bug还是预期的行为?如何使用ngx形式来破解验证?

这是一个stackblitz:

https://stackblitz.com/edit/angular-knzoth?file=src/app/app.module.ts

谢谢!

解决方法如下:

validation: (control: FormControl): ValidationErrors => {
if (!control.value) {
return of(null);
}
return control.valueChanges.pipe(
startWith(control.value),
debounceTime(500),
distinctUntilChanged(),
switchMap(value => value === "X" ? null :  {test: true}),
first()
);
}

最新更新