1
votes

I have array in Angular typescript

{
  "data": [
    {
      "name": "string",
      "description": "string",
      "chackboxes": [
        {
          "checkboxName": "string",
          "displayName": "string"
        }
      ]
    }
  ]
}

I want to create Form array inside for group with formcontrols checkBox name. Something like this -> FormArray[FormGroup[formControl, formcontrol], FormGroup[],]... so I can loop first through array and than through groups. And set checkboxes.

2

2 Answers

0
votes

"divide et impera". Make functions that received data and return FormGroup

getChackboxesGroup(data:any):FormGroup
{
    data=data || {
                   checkboxName:'',
                   displayName": ''
                  }
    return new FormGroup({
          checkboxName:new FormControl(data.checkboxName),
          displayName:new FormControl(data.displayName),
    })
}

getDataGroup(data:any):FormGroup
{
   data=data || { name: '',
                  description: '',
                  chackboxes:null
                }
   return new FormGroup({
       name:new FormControl(data.name),
       description:new FormControl(data.description),
       chackboxes:data.chackboxes?
           new FormArray(data.chackboxes.map(x=>this.getChackboxesGroup(x)):
           new FormArray([])
   })
}

Well, you only need, after received the data

this.formArray=new FormArray(this.data.map(x=>this.getDataGroup(x))

Futhermore, if you want to add a new empty element you only need

this.formArray.push(this.getDataGroup(null))

//or if you want to add a new checkboxes to the first element of the array
(this.formArray.at(0).get('chackboxes') as FormArray)
       .push(this.getChackboxesGroup(null)