I'm creating a project with a Reactive Form
; based on Recursive
Component that creates Dynamic Form
from JSON
file.
The Sources
This is an adaptation from Ionic based on Creating Dynamic Angular Forms with JSON
I Adapted the Recursive version procedures and other changes!
My code is located in Stackblitz.
I will show a reduced code version of json-form.component.html file:
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div fxLayout="column">
<ng-container *ngFor="let control of jsonFormData?.controls">
<div fxFlex="100%">
<selects
*ngIf="control.type === 'select'"
[control]="control"
[visible]="true"
></selects>
</div>
</ng-container>
</div>
<button mat-raised-button class="mt-1" color="primary">
<em class="fa fa-save">Submit</em>
</button>
</form>
As you can see the custom component is selects
.
Now, let's take a look at the Recursive
code of use of the selects
template. Again I reduce the code of select.component.html file:
<form [formGroup]="form">
<ng-container *ngIf="control?.children">
<mat-form-field
*ngIf="control.type === 'select' && control.visible"
fxFlex="100%"
hideRequiredMarker
>
<mat-label>{{ control.label }}</mat-label>
<mat-select
[formControlName]="control.name"
[placeholder]="control.label"
(selectionChange)="onSelectChange($event.value)"
>
<mat-option
*ngFor="let child of control.children"
[value]="child.value"
>
{{ child.label }}
</mat-option>
</mat-select>
</mat-form-field>
</ng-container>
<ng-container *ngFor="let child of control?.children">
<div fxFlex="100%">
<selects *ngIf="child.type === 'select'" [control]="child"></selects>
</div>
</ng-container>
</form>
The code of recursion using selects
Component is:
<ng-container *ngFor="let child of control?.children">
<div fxFlex="100%">
<selects *ngIf="child.type === 'select'" [control]="child"></selects>
</div>
</ng-container>
An example of error is:
ERROR
Error: Cannot find control with name: 'Petitioner (C2 -> P2)'
Unfortunately, I can't to find the problem in order to solve it.
Some clue in order to solve the error?
EDIT I suspect that not all components are shown inmediately, only when the Select is clicked; then the component is not still created.
siblings
and notchildren
and it doesn't havename
property – Missilesiblings
are not nested Select Component. For this example can be ignored. Sorry, I didn't catch Firstly, you need to understand the shape of your root FormGroup value. I try to understand, I'm trying to relate theFormGroup
ofSelectComponent
usingFormGroupDirective
directive. – Califate