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: "[email protected]",},{
          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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)