【发布时间】:2018-06-09 10:54:08
【问题描述】:
我从服务器获取 JSON 响应,从该服务器获取构建 FormGroup 对象所需的元数据。由于 JSON 是动态的,FormGroup 对象也是动态的,如何解析 HTML 中的 JSON 字段?
我查看了动态表单 https://angular.io/guide/dynamic-form 的角度文档,但在这里我看到它们正在将每个类对象从父 dynamic 传递给 dynamic-form-question.component.ts -form.component.ts
我的 JSON:
[
{
"key": "Basic",
"required": false,
"controlType": "section",
"children": [
{
"key": "net1",
"required": false,
"controlType": "dropdown"
},
{
"default": "",
"key": "net2",
"required": true,
"controlType": "textbox"
}
]
},
{
"key": "Advanced",
"required": false,
"controlType": "section",
"children": [
{
"key": "Area1",
"required": false,
"controlType": "sub-section",
"children": [
{
"default": "test",
"key": "key1",
"required": false,
"controlType": "dropdown",
"choices" : [ "test",
"test1",
"test2"
]
},
{
"default": "pass",
"key": "key2",
"required": false,
"controlType": "textbox"
}
]
},
{
"key": "Area2",
"required": false,
"controlType": "sub-section",
"children": [
{
"default": false,
"key": "key3",
"required": false,
"controlType": "radiobutton"
}
]
}
]
}
]
对应的FormGroup对象是:
form = this.fb.group({
Basic: this.fb.group ({
net1: '',
net2: ''
}),
Advanced: this.fb.group ({
Area1: this.fb.group ({
key1: 'test',
key2: 'pass'
}),
Area2: this.fb.group ({
key3: ''
})
})
在 HTML 中,我需要从 JSON 中获取字段,例如 controlType,以决定输入元素的类型以及下拉菜单的选择。
在 typescript 中解析 JSON 以便将其传递到 HTML 中的理想方法是什么?
基本上我想要子对象,例如,
{
"key": "net1",
"required": false,
"controlType": "dropdown"
}
与相应的 formGroup 对象一起传递给 JSON。
我的 HTML 看起来像:
<div>
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<div formGroupName="Basic">
<ng-container *ngFor="let controlName of controls('Basic.children')" formGroupName="children">
<input type="textbox" [formControlName]="controlName"><br>
</ng-container>
</div>
<div formGroupName="Advanced">
<div *ngFor="let groupName of controls('Advanced')" [formGroupName]="groupName">
<ng-container *ngFor="let controlName of controls('Advanced.' + groupName)">
<input type="textbox" [formControlName]="controlName"><br>
</ng-container>
</div>
</div>
<div class="form-row">
<button type="submit" [disabled]="!form.valid">Save</button>
</div>
</form>
</div>
这样我就可以在 controlType 上应用 ngSwitch,就像在官方网站上的示例中一样。 (到目前为止,输入元素只有一种类型。)。
有人可以帮我解决这个问题吗?
【问题讨论】:
标签: json angular angular-reactive-forms