I have an ng-container that describes all of my possible form field templates, essentially on a large switch statement depending on the field's metadata:
<ng-template #dynamicFormField let-field="inputField">
<div *ngIf="field.dataTypeName == 'ShortText'">
<mat-form-field class="col-md-6">
<input matInput type="text" [placeholder]="field.attributeLabel" [formControlName]="field.attributeName">
</mat-form-field>
</div>
<div *ngIf="field.dataTypeName == 'LongText'">
<mat-form-field class="col-md-12">
<input matInput type="text" [placeholder]="field.attributeLabel" [formControlName]="field.attributeName">
</mat-form-field>
</div>
<div *ngIf="field.dataTypeName == 'Number'">
<mat-form-field>
<input matInput type="number" [placeholder]="field.attributeLabel" [formControlName]="field.attributeName">
</mat-form-field>
</div>
<ng-template>
I have a base formgroup, then one property of the form group is a form array, each element of which with its own formgroup. For example, the data model looks something like this:
{
name: 'Article Name',
description: 'Some description of the article',
sections: [
{
sectionName: 'Rich text section',
sectionContent: 'Some rich text'
},
{
sectionName: 'Second section',
sectionContent: 'Some rich text'
}
]
}
where each of these fields has corresponding metadata describing its form properties.
I want to be able to reuse the input switch statement in both the base formgroup as well as the formgroups within the form array. However, the inside of the ng-container cannot access the formgroup specified by the formarray's formGroupName input:
<div *ngFor="let field of this.sectionTypeSchemas[section.value.sectionTypeId]">
<div *ngIf="field.isVisible != false" formGroupName="{{i}}">
<ng-container *ngTemplateOutlet="dynamicFormField;context:{ inputField:field }"></ng-container>
</div>
</div>
The error I am running into is basically that the Angular cannot find the controls that are inside of the formarray's FormGroups (i.e. sectionName from data model), although there is no issue in finding the controls corresponding the base formgroup controls (name and description from the data model). Is there a way I can manually pass the formgroup reference to the ng-container? A short example can be seen here.