As a newcomer to Angular 4, I've embarked on my first project and started learning the ropes.
I have devised a Reactive Form to showcase a form structure that looks like this:
Form (FormGroup)
|
--> aggLevels (FormArray)
|
--> aggregationLevelName (FormControl - displayed in a label)
|
--> variableDataForLevel (FormArray)
|
--> variableDataId (FormControl)
|
--> value (FormControl)
The following snippet shows the HTML component for this:
<form [formGroup]="varDataForm" (ngSubmit)="onSubmit()" novalidate>
<div formArrayName="aggLevels"
*ngFor="let agLevel of varDataForm.get('aggLevels')?.controls; let aggLevelId = index;">
<div [formGroupName]="aggLevelId">
<label>{{agLevel?.get('aggregationLevelName')?.value}}</label>
<div formArrayName="variableDataForLevel"
*ngFor="let vardata of varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls; let rowIndex = index;">
<div [formGroupName]="rowIndex">
<select formControlName="variableDataId">
<option *ngFor="let gs1 of gs1AIs" [value]="gs1.Id">{{gs1.description}}</option>
</select>
<input formControlName="value" placeholder="Value">
<div class="error" *ngIf="vardata.get('value').hasError('required') && vardata.get('value').touched">
Required
</div>
</div>
</div>
</div>
</div>
</form>
The issue arises when there are no elements in the variableDataForLevel
FormArray. The error message I encounter is as follows:
ng:///AppModuleShared/VarDataComponent.ngfactory.js:49 ERROR Error: Cannot find control with path: 'aggLevels -> 1 -> variableDataForLevel -> 0'
Despite using the safe navigation operator ?
, such as here:
varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls
The problem persists. While aggLevels
and variableDataForLevel
aren't undefined, the error remains unresolved.
How can I prevent displaying the FormArray if it's empty? Being new to Angular, I'm uncertain about fixing this issue.
This TypeScript class corresponds to the component:
(Component details here...)
My suspicion rests on this method:
createVarDataControls(varData: IVarData[]): any[] {
let array: any[] = [];
for (let vData of varData) {
let group: FormGroup;
group = this.fb.group({
variableDataId: vData.variableDataId,
value: vData.value
});
array.push(group);
}
return array;
}
If varData
turns out to be empty, an Any[]
gets returned despite my intent not to show anything empty on the form.
I revised the createVarDataControls
method to generate a FormGroup
instead of an array if varData
is empty. Although this workaround enables me to proceed without errors, it doesn't fully address the underlying issue:
(Method adjustment here...)
However, this modification results in displaying two blank controls which isn't ideal. This approach merely serves as a diagnostic tool rather than a solution.