3

The Structure of my form is as shown below

-MainForm(ParentForm)
 -FormGroup(MedicineGroup)
  -FormArray(MedicineArray)

I wanted to iterate MedicineArray for which, i did some research and wrote the below code

for (let control of soForm.get('MedicineGroup').controls['MedicineArray'].controls) {
    medObj.name.push(control.controls['MedName'].value);
  }

The code is working fine but i am getting a warning, which says

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

Is there any other or better way to iterate a FormArray which is inside a FormGroup?

2 Answers 2

7

You can try using ['controls'] instead of .controls:

for (let control of soForm.get('MedicineGroup')['controls']['MedicineArray']['controls']) {
    // ...
}

Another option would be:

const formArray = soForm.get('MedicineGroup.MedicineArray') as FormArray;
console.log(formArray);

It's a good practice to access nested controls using dot notation.

Sign up to request clarification or add additional context in comments.

Comments

5

The reason this is occurring is because the type system understands that you have an AbstractControl, because AbstractControl.prototype.get() returns an AbstractControl, but it doesn't know which concrete AbstractControl you are referencing, so accessing a controls property causes this warning.

You have some options as to how to solve it, casting or introducing another symbol, but the method is the same: provide better type information:

let aFormArray: FormArray = soForm.get('MedicineGroup.MedicineArray');

for (let c of aFormArray.controls) {
    medObj.name.push(c.controls['MedName'].value);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.