Search code examples
angularangular-reactive-formsangular7formarray

Angular and Reactive form arrays setting a form ontrol value inside form array giving error of must supply a value for form control name


I need to set a specific form control of a reactive form array to a value. I am using the following:

(<FormArray>this.formGroup.get('test')).at(i).setValue(oldFr);

Where i is the index where the change should be done, and oldFr the value to be set.

But I forgot that there is multiple form controls in each index. The form control I need to set is called formControlName="fr".

I tried:

(this.formGroup.get('test')).at(i).controls['fr'].setValue(oldFr);

But I had the following error:

ERROR Error: Must supply a value for form control with name: 'fr'

And

Cannot read property 'at' of null

How can I set a value of a form control residing inside array of controls ?


Solution

  • It sounds like you have a FormGroup with a key containing a FormArray which itself contains an array of FormGroups.

    const formGroup = new FormGroup({
      test: new FormArray([
        new FormGroup({
          fr: new FormControl('')
        })
      ])
    })
    
    formGroup.get('test').at(0).get('fr').patchValue(oldFr)