angularngx-formly

Getting unnecessary values in ngx-formly form.value


Summary:

Using ngx-formly, I want to create a form whose value is this:

[
      {
        investment_name: [
           "Investment 1",
           "Investment 2",
           "Investment 3"
        ]
      },
      {
       investor_name: [
           "John",
           "Tom",
           "Tim"
          ]
        }
  ]

What I tried:

stackblitz

I am using following field value but I am getting incorrect form.value with extra field (SEE LINE A AND B). Also it would be awesme if I could avoid "main" key but its not necessary.

  fields: FormlyFieldConfig[] = [
    {
      key: 'main',
      type: 'repeat',
      fieldArray: {
        fieldGroupClassName: 'row',
        fieldGroup: [
          {
            key: 'text',
            type: 'input-repeat',
          },
          {
            key: 'name',
            type: 'input-repeat',
          },
        ],
      },
    },
  ];

form.value I am getting is this (see LINE A AND B):

   {
      "main": [
        {
          "text": [
            "Investment 1",
            "Investment 2",
            "Investment 3"
          ],
          "name": [] // LINE A: I DONT WANT THIS
        },
        {
          "text": [], //LINE B: I DONT WANT THIS
          "name": [
            "John",
            "Tom",
            "Tim"
          ]
        }
      ]
    }

Solution

  • You have to change your fields config with the following:

      fields: FormlyFieldConfig[] = [
        {
          type: 'repeat',
          key: 'main',
          fieldArray: {
            fieldGroupClassName: 'row',
            fieldGroup: [
              {
                fieldArray:{
                type: 'input-repeat',
                key: 'text',
                }
              },
              {
                fieldArray:{
                type: 'input-repeat',
                key: 'name',
                }
              },
            ],
          },
        },
      ];
    

    I have added a fieldArray for both the text and name fields.

    This is necessary because in your model, you have an array of values instead of a single value. This is also the reason why two additional empty fields, name and text, were generated.