Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2: Property 'controls' does not exist on type 'AbstractControl'. Error when accessing .control of an object within a formarray thru an index

I'm trying to push another formbuilder within a formarray but it gives me an error since I think there are no items in the array when initializing the code, hence there are no controls. The error is Property 'controls' does not exist on type 'AbstractControl' after the

(<FormArray>this.loanTypeForm.controls['frequency']).controls[index] 

I'm using angular 2.0.0-beta.17

let settingsForm: FormArray = new FormArray([]);       (<FormArray>this.loanTypeForm.controls['frequency']).push(         this.formBuilder.group({           'name': [value, Validators.required],           'settings': settingsForm,         })       ); (<FormArray>this.loanTypeForm.controls['frequency']).controls[index].controls['settings'].push(       this.formBuilder.group({         'term': [null, Validators.required],         'eir': [null, Validators.required],       })     ); 
like image 607
deckotonic Avatar asked Jan 31 '17 05:01

deckotonic


2 Answers

You can use ['controls'] instead of .controls, as below:

(<FormArray>this.loanTypeForm.controls['frequency']).controls[index]['controls']['settings'].push(...) 

But in order to simplify and provide more readability I'd suggest you to change it all to:

const control = this.loanTypeForm.get(`frequency.${index}.settings`) as FormArray; control.push(...); 
like image 184
developer033 Avatar answered Oct 21 '22 09:10

developer033


get() is the preferred way to access form controls

this.loanTypeForm.get(`frequency.${index}.settings`) 
like image 43
Günter Zöchbauer Avatar answered Oct 21 '22 11:10

Günter Zöchbauer