Search code examples
angulartypescriptangular-formsformarrayangular-formbuilder

Angular FormGroup FormArray - submits only one object in array from dropdown


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


Solution

  • 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.