You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Formly fieldGroup用整数key时返回数组而非对象问题

解决ngx-formly fieldGroup返回数组而非对象的问题

问题场景

使用@ngx-formly/core@6.1.2和@ngx-formly/bootstrap@6.1.2时,配置fieldGroup字段组,将inventories作为父key,子字段key设为字符串形式的"3"和"4"。预期model中的inventories是包含对应键值的对象,但实际返回的是包含null元素的数组。

相关代码

package.json

"@ngx-formly/bootstrap": "^6.1.2",
"@ngx-formly/core": "^6.1.2",

app.component.html

<form [formGroup]="form" (ngSubmit)="submit()">
  <formly-form
    [model]="model"
    [fields]="fields"
    [options]="options"
    [form]="form"
  ></formly-form>
  <button type="submit" class="btn btn-primary submit-button">Submit</button>
  <button type="button" class="btn btn-default" (click)="options.resetModel()">
    Reset
  </button>
</form>

<p>{{ model | json }}</p>

app.component.ts

import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { FormlyFormOptions, FormlyFieldConfig } from '@ngx-formly/core';

@Component({
  selector: 'formly-app-example',
  templateUrl: './app.component.html',
})
export class AppComponent {
  form = new FormGroup({});
  model: any = {};
  options: FormlyFormOptions = {
    formState: {
      awesomeIsForced: false,
    },
  };

  fields: FormlyFieldConfig[] = [
    {
      key: 'inventories',
      fieldGroup: [
        {
          key: '3',
          type: 'input',
          props: {
            label: 'Text',
            placeholder: 'Formly field 3',
            required: true,
          },
        },
        {
          key: '4',
          type: 'input',
          props: {
            label: 'Text',
            placeholder: 'Formly field 4',
            required: true,
          },
        },
      ],
    },
  ];

  submit() {
    if (this.form.valid) {
      alert(JSON.stringify(this.model));
    }
  }
}

实际输出

{ "inventories": [ null, null, null, "22", "33" ] }

期望输出

{ 
  "inventories": {"3": "22", "4": "33" } 
}

解决方案

问题根源是ngx-formly默认会将纯数字形式的key识别为数组索引,自动把父字段转换为数组类型。解决方法是显式指定父字段的type为object,强制让组件将该字段当作对象处理:

修改fields配置,给inventories字段添加type: 'object':

fields: FormlyFieldConfig[] = [
  {
    key: 'inventories',
    type: 'object', // 新增这一行,强制指定为对象类型
    fieldGroup: [
      {
        key: '3',
        type: 'input',
        props: {
          label: 'Text',
          placeholder: 'Formly field 3',
          required: true,
        },
      },
      {
        key: '4',
        type: 'input',
        props: {
          label: 'Text',
          placeholder: 'Formly field 4',
          required: true,
        },
      },
    ],
  },
];

同时建议初始化model时明确设置inventories为对象,确保初始结构正确:

model: any = { inventories: {} };

这样配置后,提交表单时model.inventories就会以对象形式返回,符合预期格式。

内容的提问来源于stack exchange,提问作者mukesh patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 04:43:20