2

After adding an array of FormGroups to my form I'm not able to call setValue inside of the FormGroup

This is what I've tried:

this.formGroup.controls.formArray.get('input').setValue('test');

and

this.formGroup.get('formArray').get('input').setValue('test');

Which throws:

Cannot read property 'setValue' of null

TS:

    get formArray(): AbstractControl | null { return this.formGroup.get('formArray'); }

    this.formGroup = this.fb.group({
        formArray: this.fb.array([

            this.fb.group({

                input: [null, [Validators.required]]
            }),

            this.fb.group({

                anotherInput: [null, [Validators.required]]
            }),
        ])
    });

What am I doing wrong?

1
  • just a plain old JavaScript array, a FormArray references its element with numerical index. In your code, you have a FormArray of size 1, meaning you need to get the 0th element of the FormArray and then do something with it. What your code is missing is that it skips pulling out the 0th element of the FormArray. Commented Jul 26, 2019 at 18:18

1 Answer 1

4

a form array's controls is an array of AbstractControls, and in tihs case, you have groups in that array, so you need to access it as one:

this.formGroup.get('formArray').get('0').get('input').setValue('test');

run the get at the index of the form array corresponding to the group you want, then you can access the control on the group at that array.

you also probably want to change your getter:

get formArray(): FormArray { return this.formGroup.get('formArray') as FormArray; }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the quick answer, but get() is not taking numbers
my bad, updated answer, just needs string and i had the index wrong
What would be the improvement of using this getter that you just posted?
it declares it as a FormArray rather than an AbstractControl and you know it's not null in this case. So you'll always have the correct typings. FormArray has certain methods that AbstractControl doesn't, so typescript won't complain if you try to use them.

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.