如何解析要提供给 formcontrol 的 JSON 值? [英] How to parse JSON values to be fed to formcontrol?

查看:24
本文介绍了如何解析要提供给 formcontrol 的 JSON 值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器获得 JSON 响应,我从中获取构建 FormGroup 对象所需的元数据.既然 JSON 是动态的,FormGroup 对象也是动态的,那么如何解析 HTML 中的 JSON 字段?

我查看了动态表单的角度文档https://angular.io/guide/dynamic-form 但在这里我看到他们将每个类对象从父 dynamic-form.component.ts 传递给 dynamic-form-question.component.ts

我的 JSON:

<预><代码>[{"key": "基本",必需":假,"controlType": "节",孩子们": [{"key": "net1",必需":假,控制类型":下拉菜单"},{默认": "","key": "net2",必需":真的,控制类型":文本框"}]},{"key": "高级",必需":假,"controlType": "节",孩子们": [{"key": "区域1",必需":假,"controlType": "子节",孩子们": [{默认":测试","key": "key1",必需":假,"controlType": "下拉菜单",选择":[测试",测试1",测试2"]},{默认":通过","key": "key2",必需":假,控制类型":文本框"}]},{"key": "区域2",必需":假,"controlType": "子节",孩子们": [{默认":假,"key": "key3",必需":假,控制类型":单选按钮"}]}]}]

对应的 FormGroup 对象是:

form = this.fb.group({基本:this.fb.group ({网络 1: '',网络2:''}),进阶:this.fb.group ({区域1:this.fb.group({键 1: '测试',key2:'通过'}),区域2:this.fb.group({键 3: ''})})

在 HTML 中,我需要从 JSON 中获取字段,例如 controlType 来决定输入元素的类型以及下拉列表的选择.

解析打字稿中的 JSON 以便将其传递到 HTML 的理想方法是什么?

基本上我想要子对象,例如

<代码>{"key": "net1",必需":假,控制类型":下拉菜单"}

与相应的 formGroup 对象一起传递给 JSON.

我的 HTML 看起来像:

<form (ngSubmit)="onSubmit()" [formGroup]="form"><div formGroupName="基本"><ng-container *ngFor="let controlName of controls('Basic.children')" formGroupName="children"><input type="textbox" [formControlName]="controlName"><br></ng-容器>

<div formGroupName="高级"><div *ngFor="let groupName of control('Advanced')" [formGroupName]="groupName"><ng-container *ngFor="let controlName of controls('Advanced.' + groupName)"><input type="textbox" [formControlName]="controlName"><br></ng-容器>

<div class="form-row"><button type="submit" [disabled]="!form.valid">保存</button>

</表单>

这样我就可以像官网上的例子一样在controlType上应用ngSwitch.(截至目前,输入元素只有一种类型.).

有人可以帮我解决这个问题吗?

解决方案

我刚刚做了一个解决方案,它可能有一些问题,它不是那么动态,但它仍然可以帮助

这是我的模板:

<div *ngFor="让输入的输入"><输入[类型]="输入">

</表单>

我完全复制了您的 JSON 示例并用它来为我的解决方案建模

这是组件.ts

导出类 HomeComponent 实现 OnInit {输入:数组<字符串>= [];json 示例:对象;构造函数(){}ngOnInit() {this.json 示例 =[{"key": "基本",必需":假,"controlType": "节",孩子们": [{"key": "net1",必需":假,控制类型":下拉菜单"},{默认": "","key": "net2",必需":真的,控制类型":文本框"}]},{"key": "高级",必需":假,"controlType": "节",孩子们": [{"key": "区域1",必需":假,"controlType": "子节",孩子们": [{默认":测试","key": "key1",必需":假,"controlType": "下拉菜单",选择":[测试",测试1",测试2"]},{默认":通过","key": "key2",必需":假,控制类型":文本框"}]},{"key": "区域2",必需":假,"controlType": "子节",孩子们": [{默认":假,"key": "key3",必需":假,控制类型":单选按钮"}]}]}];this.parseJSON();}parseJSON() {Object.keys(this.jsonExample).forEach(key => {Object.keys(this.jsonExample[key]['children']).forEach(key2 => {if (this.jsonExample[key]['children'][key2]['controlType'] === 'sub-section') {Object.keys(this.jsonExample[key]['children'][key2]['children']).forEach(key3 => {this.inputs.push(this.jsonExample[key]['children'][key2]['children'][key3]['controlType']);});}别的 {this.inputs.push(this.jsonExample[key]['children'][key2]['controlType']);}});});}}

所以基本上我正在检查每个 controlType 键,然后将它的值添加到一个数组中,然后使用 *ngFor 和数据绑定,这里并不是你想要的所有东西,但你可以做一些更改以获得更多值出对象.我希望这会有所帮助

I get JSON reponse from the server from which I take the metadata required to build the FormGroup object. Since the JSON is dynamic and so is FormGroup object, how to parse the JSON fields in HTML?

I looked at the angular documentation for dynamic forms https://angular.io/guide/dynamic-form but here I see they are passing each class object to the dynamic-form-question.component.ts from the parent dynamic-form.component.ts

My 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"
                }
            ]
        }
    ]
  }
]

for which the corresponding FormGroup Object is:

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: ''
  })
})

In the HTML I need to get the fields from the JSON like controlType to decide on the type of input element and also the choices in case of a dropdown.

What would be ideal way to parse the JSON in the typescript so that it can be passed onto the HTML?

Basically I want the child object eg,

{
    "key": "net1",
    "required": false,
    "controlType": "dropdown"
}

to be passed to JSON along with the corresponding formGroup object.

My HTML looks like:

<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>

so that I can apply ngSwitch on the controlType just like in the example on the official website. (As of now the input element is of one type only. ).

Can someone help me out with this?

解决方案

I just did a solution, there might be a few things wrong with it, and it is not that dynamic, but it could still help

this is my template:

<form novalidate >
    <div *ngFor="let input of inputs">
        <input [type]="input">
    </div>
</form>

i completely copied your JSON Example and used that to model my solution

this is the component.ts

export class HomeComponent implements OnInit {

  inputs: Array<String> = [];

  jsonExample: Object;


  constructor() { 


  }

  ngOnInit() {

this.jsonExample = 
[
  {
    "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"
                }
            ]
        }
    ]
  }
];

this.parseJSON();



}

  parseJSON() {

    Object.keys(this.jsonExample).forEach(key => {
      Object.keys(this.jsonExample[key]['children']).forEach(key2 => {
        if (this.jsonExample[key]['children'][key2]['controlType'] ===  'sub-section') {
          Object.keys(this.jsonExample[key]['children'][key2]['children']).forEach(key3 => {
            this.inputs.push(this.jsonExample[key]['children'][key2]['children'][key3]['controlType']);
          });
        }
        else {
          this.inputs.push(this.jsonExample[key]['children'][key2]['controlType']);
        }
      });
    });

  }

}

so basically I am checking for every controlType key and then adding the value of it to an array, then using *ngFor and data binding, not everything you wanted is in here, but you could do some changes to also get more values out of the object. I hope this helps

这篇关于如何解析要提供给 formcontrol 的 JSON 值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆