arraysangularangular-reactive-forms

How to pass array with multiple objects to Angular FormControl?


Let's say I have an object with string values like this:

data = { input: '', description: '' }

where input is what user typed, that I grabbed in (change) function and description is what I have programmatically added in the function afterwards.

I'm passing an array of data objects to formControl with this.form.patchValue({control: this.array}) but when I check against it with this.form.get('control').value it returns an array with only first object (array[0]).

How do I get it to return entire array ?


Solution

  • Ensure that you must create the N (number) of the FormGroup instance in your control FormArray based on the number of objects in your array before the patchValue().

    this.form = new FormGroup({
      control: new FormArray([]),
    });
    
    for (let data of this.array) {
      (this.form.controls['control'] as FormArray).push(
        new FormGroup({
          input: new FormControl(),
          description: new FormControl(),
        })
      );
    }
    
    this.form.patchValue({ control: this.array });
    

    You can also assign the value to the FormControl when initializing the FormGroup instance.

    for (let data of this.array) {
      (this.form.controls['control'] as FormArray).push(
        new FormGroup({
          input: new FormControl(data.input),
          description: new FormControl(data.description),
        })
      );
    }
    

    Demo @ StackBlitz