Search code examples
angulardrop-down-menuangular-formsformarrayangular-formbuilder

Angular Form merge data from select dropdown menus


How to merge values from dropdown menus into array of objects? There are two dropdown menus (persons and countries) with pre populate values enter image description here

so when assigning country to person, I'm trying to get data in array of objects like: [{person: 'John', country: 'USA'}, {person: 'Pablo', country: 'Mexico'}] based on user selection.

I'm trying with FormArray but I'm doing something wrong

Stackblitz


Solution

  • You need to add a formGroup to formArray base on the number of persons data so if you have two person you have to create two formGroup

    like this

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

    or greate a formGroup base on the persons

    this.selectForm = this.formBuilder.group({
      persons: this.formBuilder.array(this.getFormGroupByN(this.personsData.length)
      )
    });
    
    
    getFormGroupByN(n: number) {
      let result = []
      for (let i = 0; i < n; i++) {
        result.push(this.formBuilder.group({
          'person': '',
          'country': ''
        })
        );
      } // for end 
    
      return result;
    }
    

    I have create a variable to hold the persons data caled personsData so Ican loop throw and create option element

    this.personsData = this.parts.map(part => part.persons).reduce((r, part, []) => r.concat(part));
    

    the result now look like this

    [{"person":"John","country":"USA"},{"person":"Pablo","country":"Mexico"}]
    

    stackblitz demo