1
votes

I want to generate JSON driven form with array of object, currently stackbiz is working on single object json (person.js), I am trying to modify person.ts with below array of JSON

for json

[{
  name: {
    label: 'Name',
    value: 'Juri',
    type: 'text',
    validation: {
      required: true
    }
  },
  age: {
    label: 'Age',
    value: 32,
    type: 'text'
  },
  gender: {
    label: 'Gender',
    value: 'M',
    type: 'radio',
    options: [
      { label: "Male", value: 'M'},
      { label: "Female", value: 'F'}
    ]
  }, 
  city: {
    label: 'City',
    value: '39010',
    type: 'select',
    options: [
      { label: "(choose one)", value: ''},
      { label: "Bolzano", value: '39100'},
      { label: "Meltina", value: '39010'},
      { label: "Appiano", value: '39057'}
    ],
    validation: {
      required: true
    }
  }
},
{
  name: {
    label: 'Name',
    value: 'Juri1',
    type: 'text',
    validation: {
      required: true
    }
  },
  age: {
    label: 'Age',
    value: 32,
    type: 'text'
  },
  gender: {
    label: 'Gender',
    value: 'M',
    type: 'radio',
    options: [
      { label: "Male", value: 'M'},
      { label: "Female", value: 'F'}
    ]
  }
}]

So template output should be something like this (including both section)

enter image description here

enter image description here

The issue which Im facing in above multi object json is that I looping through array of object and creating formGroup with new formControl in loop, and then try to push into formArray outside of loop but not success, any help or suggestion appreciated, I stuck in formArray vs FormBuilder vs FormGroup and now brain is not working :(

here is plunker link I am trying to modify : https://stackblitz.com/edit/angular-dynamicforms-blogarticle-fjkjx4

1

1 Answers

0
votes

You can just create an empty formArray to store the responses.
https://stackblitz.com/edit/angular-dynamicforms-blogarticle-jns9xq

public formResponses: FormArray = new FormArray([]);
  onSubmit(form) {
    if (form.valid) {
      this.formResponses.push(new FormControl(form.value));
    }
  }