form builder angular 2 - How to construct an array of controls?
Asked Answered
S

1

6

I'm trying to create a form builder to generate from it a specific JSON format body to put it on server, the problem that i'm having is how to represent an array of task like indicated in my code ,here is my format builder :

    this.form = fb.group({          
               Action: fb.group({
                label: [],
                actionType: [],
                description: [],
                HTTPMethod: [],
                ressourcePattern: [],
                status: [],
                parameters: [],
                linkedprocess: fb.group({
                process: fb.group({
                    label: []
                }),
                /////////////////////
                associatedTasks:[],     // => here i want to represent the associated tasks
                    task: fb.group({   // it's an array of task 
                        label:[]
                    })
                /////////////////////
               }),
                labelParam: [],
                descriptionParam: []
               })
            });
    

and here is my json format that i want to get from my form:

    {"Action":       {
             "label": "A7791",
             "HTTPMethod": "POST",
             "actionType": "indexation",
             "status": "active",
             "description": "descroption new",
             "resourcePattern": "",
             "creationDate": "30-05-2016 06:14:09",
             "modificationDate": "13-06-2016 11:51:10",
             "parameters": [],
             "linkedProcess": {"Process": {"label": "P1"}},
             "associatedTasks": [{"Task": {"label": "T1"}}]
          }}
    

it doesn't work like this :

    associatedTasks:[
                  task: fb.group({
                    label:[]
                })
    ]

i've tested Daniel solution it's cool but it's not binding to my template, here is my html :

`

<div class="form-group" >
    <label for="Task">associatedTasks</label>
    <select
        ngControl="Task" #frequency="ngForm" 
        id="Task" class="form-control" 
        required>
        <option value=""></option>
        <option *ngFor="#taske of associatedTaskss" value="{{ taske.id }}" >
           {{ taske.label}}
        </option>
    </select> 
 `

i'm getting the error (Cannot find control 'Task' in [Task in ])

note that associatedTaskss is the list of tasks that i'm getting from server ( right now just testing it like this :

`
 associatedTaskss=[
        {id :1, label:'T1'},
        {id :2, label:'T2'},
        {id :3, label:'T3'},
        {id :4, label:'T4'}
    ];
` 

and here is the JSON format that i'm putting on server (exemple prefilled with some data)

`

"Action": {
          "label": "A1",
          "HTTPMethod": "POST",
          "actionType": "indexation",
          "status": "active",
          "description": "Ajout d'une transcription dans le lac de données",
          "resourcePattern": "transcriptions/",
          "parameters": [
            {
              "Parameter": {
                "label": "",
                "description": "Flux JSON à indexer",
                "identifier": "2",
                "parameterType": "body",
                "dataType": "json",
                "requestType": "Action",
                "processParameter": {
                  "label": "",
                  "description": "Flux JSON à indexer",
                  "identifier": "4",
                  "parameterType": "body",
                  "dataType": "json",
                  "requestType": "Process"
                }
              }
            },
            {
              "Parameter": {
                "label": "collection",
                "description": "Identifiant d'une collection dans la base de données orientée document",
                "identifier": "10",
                "parameterType": "URI",
                "dataType": "string",
                "defaultValue": "transcriptions",
                "requestType": "Action",
                "processParameter": {
                  "label": "collection",
                  "description": "Identifiant d'une collection dans la base de données orientée document",
                  "identifier": "1",
                  "parameterType": "URI",
                  "dataType": "string",
                  "requestType": "Process"
                }
              }
            }
          ],
          "linkedProcess": {
            "Process": {
              "label": "P1"
            }
          },
          "associatedTasks": [
            {
              "Task": {
                "label": "T1"
              }
            }
          ]
        }

`

Starlastarlene answered 15/6, 2016 at 13:5 Comment(0)
L
4

To include arrays in your form group you'll have to use the FormBuilder.array() function.

is this what you want?

this.form = _fb.group({
  Action: _fb.group({
    label: [],
    HTTPMehotd: [],
    actionType: [],
    status: [],
    description: [],
    resourcePattern: [],
    creationDate: [],
    modificationDate: [],
    parameters: _fb.array([]),
    linkedProcess: _fb.group({
      Process: _fb.group({
        'label': []
      })
    }),
    associatedTasks: _fb.array([
      _fb.group({
        Task: _fb.group({
          label: []
        })
      })  
    ])
  })
})
Livre answered 15/6, 2016 at 15:54 Comment(5)
Thank you man, that's what i was looking for, i'll test it and i'll give you feedbackStarlastarlene
Let me see if I got this right. associatedTasks is an array of Tasks{id: number, label: string} ?Livre
Ok. But why do you need to have controls for the options and not just for the selections? I'm not sure, but you can't bind a control to an option. It doesn't make sense. Are you sure you understood the usage of controls in angular 2?Livre
i'm sorry, i did not understand well what you're trying to say, but what i'm aiming for is to bind the associatedTasks Array (all the tasks from my option box in my template) with the associatedTasks on my format builder (to get all the fields and deliver it to the server to add an action with the these params ) i'll post the json format that i'm trying to put on server (look up on the question)Starlastarlene
Hi I haven't read through your question but I guess this is something going to help or at least give you some insight. scotch.io/tutorials/…Arboreal

© 2022 - 2024 — McMap. All rights reserved.