这是我的问题。
Online Example of the issue
我有一个需要转换为表单的动态 JSON。因此,我使用了响应式表单,并通过检查 JSON 的所有属性,以这种方式创建了 FormGroup 或 FormControl:
sampleJson ={prop1:"value1", prop2: "value2",...}
...
myForm: FormGroup;
myKeys=[];
...
ngOnInit() {
this.myForm = this.getFormGroupControls(this.sampleJson, this.myKeys);
}
getFormGroupControls(json:any,keys): FormGroup{
let controls = {};
let value = {};
for (let key in json) {
if (json.hasOwnProperty(key)) {
value = json[key];
if (value instanceof Object && value.constructor === Object) {
keys.push({"key":key,children:[]});
controls[key] = this.getFormGroupControls(value,keys[keys.length-1].children);
} else {
keys.push({"key":key,children:[]});
controls[key] = new FormControl(value);
}
}
}
return new FormGroup(controls);
}
这样做之后,我使用递归模板来构建表单,如果我不使用递归模板,我会让表单工作。但是使用递归模板我收到错误:
<form [formGroup]="myForm">
<div class="form-group">
<ng-template #nodeTemplateRef let-node>
<div class="node">
<div *ngIf="node.children.length">
{{"section [formGroupName]="}} {{ getNodeKey(node) }}
<section style="display:block;margin:20px;border:solid 1px blue;padding-bottom: 5px;"
[formGroupName]="getNodeKey(node)" >
<h1>{{ node.key }}</h1>
<ng-template
ngFor
[ngForOf]="node.children"
[ngForTemplate]="nodeTemplateRef">
</ng-template>
</section>
{{"end of section"}}
</div>
<div *ngIf="!node.children.length">
<label [for]="node.key">{{node.key}}</label>
<input type="text" [id]="node.key"
class="form-control">
</div>
</div>
</ng-template>
<ng-template *ngFor="let myKey of myKeys"
[ngTemplateOutlet]="nodeTemplateRef"
[ngTemplateOutletContext]="{ $implicit: myKey }">
</ng-template>
</div>
FormerComponent.html:25 ERROR Error: Cannot find control with name: 'road'
这对应于这个示例 JSON:
"address": {
"town": "townington",
"county": "Shireshire",
"road": {
"number": "1",
"street": "the street"
}
I have 正在显示,所以我知道元素在那里。我错过了什么?
最佳答案
或者,如果您仍然需要表单组/控件层次结构,您可以通过递归传递它们来使用 formGroup 和 formControl 指令(而不是 formGroupName 和 formControlName)
Stackblits link
注意:这里有同样的问题:Recursive ReactiveForm cannot find formGroups inside of template
关于angular - 带有动态递归模板的响应式(Reactive)表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59775515/