1

I'm trying to create array of objects from dropdown values:

enter image description here

so the result of selected values from the picture would be [{person: 'John', country: 'USA'}, {person: 'Pablo', country: 'Mexico'}] , but form submits only last object.

Stackblitz

2 Answers 2

2

Problem is that you're creating only 1 FormGroup:

this.selectForm = this.formBuilder.group({
  persons: this.formBuilder.array([
    this.formBuilder.group({
      'person': '',
      'country': ''
    })
  ])
})

You should be doing an iteration of this.parts to dynamically create them:

const persons = <FormArray>this.selectForm.get('persons');

this.parts.forEach((part) => {

  part.persons.forEach((person) => {
    persons.push(this.formBuilder.group({country: null, name: person.name}));
  })
});

This will give you two FormGroup instances, each having a country and a name property. This is a more straight-forward way of doing it and it's not as messy as your current solution. You'll have to update the template accordingly.

Sign up to request clarification or add additional context in comments.

Comments

0

You probably are duplicating formControls instead of creating new ones inside the ngFor loop. Add unique names to form controls for every iteration, it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.