首页 > 解决方案 > 如何使用 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

谢谢!

标签: angularngx-formly

解决方案


解决如下:

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()
  );
}

推荐阅读