angular - 如何使用 ngx-formly 通过 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};
})
}
]
}
我观察到的是,无论指定的去抖如何,验证器都会立即运行。
此外,模型会通过去抖动更新,而角度形式会立即更新。
这是一个错误还是预期的行为?你如何使用 ngx-formly 去抖动验证?
这是一个堆栈闪电战:
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()
);
}
推荐阅读
- ios - 辞职代码签名不会将 codeDirectory 更改为 20500
- docker - 是否可以将特定用户的 ssh 连接传递到 docker 容器中?
- java - 如何根据 Java 中的用户输入格式化日历
- mongodb - 如何使用聚合填充数组内的字段
- android - Flow 在 kotlinx-coroutines-android:1.5.0 中不可用?
- javascript - 更改 css 文件中的每个相同 css 属性
- amazon - 2021 年 7 月后需要解决亚马逊 MWS API 中的 [Country_of_origin =NULL] 错误
- python - 数据框行中内容的修剪/截断平均值
- javascript - 重复 div 的背景图像
- javascript - 为什么我的 nextjs 应用无法在 Safari 上运行?