Search code examples
angularformsdatatableformarray

Angular - How to initiate FormArray from an existing array?


I would like to create an editable table with FormArray.

For this, I have the results attribute that is rendered in the table.

What's the proper way to initialize it with FormArray data?

results: Array;
tableForm: FormGroup;

ngOnInit(private fb: FormBuilder) {
  this.tableForm = this.fb.group({
    arrayForm: this.fb.array([])
  });
}

Solution

  • A form array is a bundle of form controls (as a reminder, a form group is a form control).

    In the following I will assume your results are model-related, such as

    [
      { id: 1, title: 'title 1' },
      { id: 2, title: 'title 2' },
    ]
    

    (If not, feel free to explain to me what the results are)

    Since a form array must accept controls, you will have to map your results to comply with the signature.

    You can do it with this :

    ngOnInit(private fb: FormBuilder) {
     this.tableForm = this.fb.group({
       arrayForm: this.fb.array(this.results.map(r => this.fb.group(r)))
     });
    }
    

    With this, your form array will contain a form group, made of all the properties in your object.

    Is this what you wanted or not ?