Angular formBuilder 使用 ValidatorFn 从 jsonfconfig 字符串创建控件

问题描述

您可以在此处找到 stackblitz 中的项目: https://stackblitz.com/edit/form-dynamic

我正在尝试从这样的 JSON 配置创建一个响应式表单:

    export const jsonConfigForm = {
      title: "Dynamic form test",className: "d-form",fields: [
        {
          name: "Email",type: "email",validators: ["Validator.required","Validator.minLength(5)"],customValidator: [],className: "d-form__email",value: "info@prova.it",},{
          name: "Autocomplete",type: "autocomplete",options: [
            { label: "Select one",value: "" },{ label: "Uno",value: "uno" },{ label: "Due",value: "due" },{ label: "Tre",value: "tre" },],validators: ["required"],value: "uno",};

当我尝试从字段配置创建控件时,验证器数组字符串会引发错误。 这是我的代码

    export interface FieldConfig {
      name: string;
      type: string;
      options?: Array<OptionsConfig>;
      validators?: Array<ValidatorFn>;
      customValidator?: Array<string>;
      className?: string;
      value?: any;
    }
    
    get formFields(): Array<FieldConfig> {
        return this.jsonExist && this.jsonConfig.fields;
      }
    formGroupContainer: FormGroup = this.fb.group({});
    
    ngOnInit() {
        this.formFields?.forEach((field: FieldConfig) => {
          this.formGroupContainer.addControl(
            field.name,this.fb.control(field.value,field.validators)
          );
        });
      }

这是错误

    Types of property 'fields' are incompatible.
        Type '({ name: string; type: string; validators: string[]; customValidator: any[]; className: string; value: string; options?: undefined; } | { name: string; type: string; options: { label: string; value: string; }[]; validators: string[]; customValidator: any[]; className: string; value: string; })[]' is not assignable to type 'FieldConfig[]'.
          Type '{ name: string; type: string; validators: string[]; customValidator: any[]; className: string; value: string; options?: undefined; } | { name: string; type: string; options: { label: string; value: string; }[]; validators: string[]; customValidator: any[]; className: string; value: string; }' is not assignable to type 'FieldConfig'.
            Type '{ name: string; type: string; validators: string[]; customValidator: any[]; className: string; value: string; options?: undefined; }' is not assignable to type 'FieldConfig'.
              Types of property 'validators' are incompatible.
                Type 'string[]' is not assignable to type 'ValidatorFn[]'.
                  Type 'string' is not assignable to type 'ValidatorFn'.
    
    this.jsonConfig = jsonConfigForm;

如何使用 FormControljsonConfig 文件创建带有验证器的 FormBuilder

您可以在这里找到 stackblitz 中的项目https://stackblitz.com/edit/form-dynamic

解决方法

FormControl 构造函数(或 this.fb.control(),基本上是一个调用 FormControl 构造函数的辅助方法)需要 ValidatorFn 或 ValidatorFn[] 作为第二个参数。查看您的界面,您正在提供字符串 - 因此它会引发编译错误。这是类型不匹配。因此,您需要将这些转换为与 ValidatorFn 签名匹配的真实验证器函数。

我在分叉的 stackblitz 中提供了一个简单的实现。

注意 this.fb.control(field.value,this.parseValidators(field.validators)) 中的 private parseValidators(validatorStrings: string[]): ValidatorFn[] 和相关的 FormsComponent。这是一个仅处理一个验证器的示例实现,但应该可以让您开始了解它的工作原理。

当然,这是一个有点肮脏的解决方案 - 您可能希望以不同的方式解决它(例如 FieldConfig 是类而不是接口,ValidatorFn[] 作为验证器,并且它们在构造函数中被解析)。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...