Angular 2: Accessing data from FormArray
One liner as an option to the current accepted answer
var item = (<FormArray>this.checkoutFormGroup.get('products')).at(index);
Just cast that control to array
var arrayControl = this.checkoutFormGroup.get('products') as FormArray;
and all its features are there
var item = arrayControl.at(index);
Angular 14
Angular users rejoice, since Angular v14, you can type FormGroup
, FormArray
& FormControl
, which means you no longer have to cast the AbstractControl
s.
With the given code:
const formGroup = new FormGroup({
list: new FormArray([
new FormControl('first'),
new FormControl('second'),
]),
});
You can now directly do:
const firstValue = formGroup.controls.list.at(0); // string | null
const secondValue = formGroup.controls.list.at(1); // string | null
If you want a stricter typing which exclude the null
value, you can create your FormControl
with the nonNullable
option set to true
:
const control = new FormControl('value', {nonNullable: true});
const value = control.value; // string
Anguler 13 & earlier
While casting the AbstractControl to a FormArray before using the at()
method is a way of doing it, I haven't seen anybody pointing out that you can also do it using the get()
method, which requires no casting.
According to Angular's Documentation, the signature of get()
is:get(path: string | (string | number)[]): AbstractControl | null
Which means you can also access FormArray's controls with it.
Example:
const formGroup = new FormGroup({
list: new FormArray([
new FormControl('first'),
new FormControl('second'),
]),
});
const firstValue = formGroup.get('list.0').value; // Returns 'first'
const secondValue = formGroup.get('list.1').value; // Returns 'second'
This is really useful, when you want to bind a FormControl in the HTML, where you can't cast anything:
<input [formControl]="formGroup.get('list.0')">
Here is a summary of ways of doing it:
const firstControl = listControl.get('list.0');
const firstControl = listControl.get(['list', 0]);
const firstControl = listControl.get('list').get('0'); // You need a string and not a number
const listControl = formGroup.get('list') as FormArray;
const firstControl = listControl.at(0);