Home > Enterprise >  Reactive forms render array inside an inner object
Reactive forms render array inside an inner object

Time:11-29

I have the default strictest setting in my typescript. I have the following form set-up:

this.myForm = this.fBuilder.group({
  data: this.fBuilder.group({
    program_types: this.fBuilder.array([])
  })
});

Which works.

But the template throws an error when trying to do:

<form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value)" #form="ngForm">
    <div formGroupName="data">
        <div  formArrayName="program_types">
            <ng-container
                *ngFor="let program_type of myForm.controls.data.controls.program_types.controls; let i=index">
                <ng-container [formGroupName]="i">

                </ng-container>
            </ng-container>
        </div>
    </div>
</form>

Error: Property 'controls' does not exist on type 'AbstractControl<any, any>'.

I then tried: *ngFor="let program_type of myForm.get('data.program_types')['controls']; let i=index"

But that then gave in this error: Element implicitly has an 'any' type because expression of type '"controls"' can't be used to index type 'AbstractControl<any, any>'.

Any ideas?

CodePudding user response:

AbstractControl is the base class for Form group which is why you get this error, using getters is an easy way of solving this problem.

get program_types(){
  return this.myForm.get('data')?.get('program_types') as FormArray
}
<ng-container
  *ngFor="let program_type of program_types.controls; let i = index"
>
  <ng-container [formGroupName]="i"> </ng-container>
</ng-container>
  • Related