1

尝试实现:根据用户使用 ngx-formly/material 选择区域设置 JSON 的动态表单。如何用我的对象数组“this.fields2”映射字段?

在我的 component.ts 中,我有:

model: any = {};
options: FormlyFormOptions = {};
fields: FormlyFeildCongif[];

Fetching the JSON of the selected Locale:
 ngOnInit():void
{
    this.langService.getSelectedLocaleData(this.cuurentLang).subscribe(
    (res) =>
    {
        this.myDynamicForm = res.yBank.fields;
        this.dynamicFormCreate(this.myDynamicForm);
    });
}

public dynamicFormCreate(arr:any)
{
    for(i=0; i< arrr.lenght; i++)
    {
        //here I am fetching data from json and creating an Object structure which is accepted by formly feilds
        //the problem is how do I map this.fields2 array of objects with the formly feilds
        this.fields2.push(
        {
            key: arr[i].type,
            type: arr[i].type,
            templateOptions:
            {
                label: arr[i].label,
                placeHolder: arr[i].placeHolder,
                description: arrp[i].description,
                required: true
            }
        });
    }
}

我的 component.html

<form [formGroup]="myForm">
    <formly-form
    [model]="model
    [fields]="fields"
    [options]="options"
    [form]="myForm">
    </formly-form>
</form>
4

1 回答 1

1

如果我正确理解了您的问题,那么您有几种方法可以解决此问题:

  1. 将 fields2 分配给字段

    假设你的 this.fields2 也是一个 FormlyFieldConfig[],只需将它分配给 ngOnInit 中的 formly 字段

    ngOnInit() {
     this.langService.getSelectedLocaleData(this.cuurentLang).subscribe(...);
     this.fields = this.fields2;
  1. 在 dynamicFormCreate 方法中使用 this.fields

    或者您可以直接在订阅中更新 this.fields(而不是使用 fields2)。

public dynamicFormCreate(arr:any)
{
    for(i=0; i< arrr.lenght; i++)
    {
        //here I am fetching data from json and creating an Object structure which is accepted by formly feilds
        //the problem is how do I map this.fields2 array of objects with the formly feilds
        this.fields.push(); // USING fields instead of fields2
    ...
  1. 为字段配置使用 JSON 文件并简单地从服务生成模型 在我最近的工作实现之一中,我在 JSON 文件中定义了字段,而模型就像您的情况一样来自服务。formly 库的强大之处在于这种分离,它会通过将模型应用于表单配置来自动生成表单。我正在使用重复部分,我的配置 json 相当简单,而模型从后端获取多行并正式处理/呈现它。因此,除非您有一些非常复杂的渲染需求,而静态定义的配置 JSON 不可行,否则我会推荐选项 3。
于 2020-08-11T15:44:45.630 回答