How to parse JSON values to be fed to formcontrol?

时光怂恿深爱的人放手 提交于 2019-12-11 12:19:33

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/50773488/how-to-parse-json-values-to-be-fed-to-formcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!