Home > OS >  Form array only showing one item
Form array only showing one item

Time:11-27

I am using reactive forms with a form builder to populate my form.

I defined my form like this:

public myForm = this.formBuilder.group({
  something: [''],
  people: this.formBuilder.array([this.newPerson()]),
});

The newPerson() function looks like this:

public newPerson(): FormGroup {
  return this.formBuilder.group({
    firstName: [''],
    lastName: [''],
  },);
}

In OnInit() I want to populate this form with some data and here is where I have issues. If I do:

this.getPeople().patchValue([
  { firstName: 'Bla', lastName: 'Bla' },
  { firstName: 'Test', lastName: 'Test' }, 
]);

I only see the Bla Bla in my form but not Test Test. Why is that so?

CodePudding user response:

this.formBuilder.array([this.newPerson()]) => this creates a formArray with single formGroup. You'd have to call this.newPerson() twice to create 2 formgroups, and then patchValue

public myForm = this.formBuilder.group({
  something: [''],
  people: this.formBuilder.array([this.newPerson(), this.newPerson()]),
});
  • Related