1

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

2
  • 1
    A form array is used for the *ngFor. check out stackoverflow.com/questions/52530584/… . Commented Sep 27, 2018 at 11:52
  • That's right, thanks. Is there a way to push all objects from form to array? It submits only last object stackblitz.com/edit/… Commented Sep 27, 2018 at 12:43

1 Answer 1

0

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

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

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.