Angulrar 正式的 fieldGroup 不适用于键为整数的字段

问题描述 投票:0回答:1

角度形式的 fieldGroup 应该是对象,但它返回数组作为值。

根据正式的字段配置,模型对象中的 inventory 属性应该在对象中,但它给出了数组。

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>
<!-- Copyright 2021 Formly. All Rights Reserved.
    Use of this source code is governed by an MIT-style license that
    can be found in the LICENSE file at https://github.com/ngx-formly/ngx-formly/blob/main/LICENSE -->

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 3',
            required: true,
          },
        },
      ],
    },
  ];

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

下面是上面代码中模型的输出(看起来像错误)

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

表单模型的预期输出。

{ 
  "inventories": {"3": "22", "4": "33" } 
}
angular angular-formly ngx-formly
1个回答
0
投票

需要一些小的调整:

  1. 首先为模型添加合适的类型定义:
export type FormModel = {
  inventories: {
    [index: number | string]: string;
  };
};
  1. 接下来,对你的方法稍作修改:
  changeModel() {
    this.model = {
      inventories: {
        text: 'new text',
      },
    };
  }

>> 在线查看 Stackblitz 示例

© www.soinside.com 2019 - 2024. All rights reserved.