Angular 2: Accessing data from FormArray

Sumit Agarwal picture Sumit Agarwal · Nov 17, 2016 · Viewed 50.1k times · Source

I have prepared a from using ReactiveForms provided by angular2/forms. This form has a form array products:

this.checkoutFormGroup = this.fb.group({
            selectedNominee: ['', Validators.required],
            selectedBank: ['', Validators.required],
            products: productFormGroupArray
        });

productFormGroupArray is a array of FormGroup Objects.I fetched the controls i.e. FormArray object using this:

this.checkoutFormGroup.get('products')

I am trying to get the element in the products array at index i. How can this be done without looping through the array?

Edit:

I tried with at(index) method available:

this.checkoutFormGroup.get('products').at(index)

but this is generating an error as:

Property 'at' does not exist on type 'AbstractControl'.

Edit 2: checkoutData and fund are received from server.

this.checkoutData.products.forEach(product => {
                    this.fundFormGroupArray.push(this.fb.group({
                        investmentAmount: [this.fund.minInvestment, Validators.required],
                        selectedSubOption: ['', Validators.required],
                    }))
            });

Answer

Radim Köhler picture Radim Köhler · Nov 17, 2016

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);