【发布时间】:2022-01-22 10:22:24
【问题描述】:
我正在使用Reactive Form 创建一个项目;基于Recursive 组件从JSON 文件创建Dynamic Form。
来源
这是 Ionic 基于Creating Dynamic Angular Forms with JSON 的改编
我改编了递归版本程序和其他更改!
我的代码位于Stackblitz。
我将展示 json-form.component.html 文件的简化代码版本:
<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>
如您所见,自定义组件是 selects。
现在,让我们看一下 selects 模板的Recursive 使用代码。我再次减少了 select.component.html 文件的代码:
<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>
使用selects组件的递归代码为:
<ng-container *ngFor="let child of control?.children">
<div fxFlex="100%">
<selects *ngIf="child.type === 'select'" [control]="child"></selects>
</div>
</ng-container>
错误示例如下:
ERROR
Error: Cannot find control with name: 'Petitioner (C2 -> P2)'
很遗憾,我找不到问题来解决它。
一些线索可以解决错误?
EDIT 我怀疑并非所有组件都会立即显示,只有在单击 Select 时才会显示;那么组件还没有被创建。
【问题讨论】:
-
首先,您需要了解根 FormGroup 值的形状,然后使用嵌套控件生成该 FormGroup。我不明白最嵌套的配置:你为什么使用
siblings而不是children并且它没有name属性 -
@yurzui
siblings没有嵌套选择组件。对于这个例子可以忽略。抱歉,我没听懂首先,您需要了解根 FormGroup 值的形状。我试图理解,我正在尝试使用FormGroupDirective指令关联SelectComponent的FormGroup。 -
您只创建了顶级 FormGroup 并始终引用该根 FormGroup。
-
@yurzui 非常感谢您的宝贵时间。现在,我需要知道如何解决它!。
-
这里是另一个例子dev.to/julianobrasil/…
标签: angular angular-material angular-reactive-forms recursive-component angular-dynamic-forms