Search code examples
angularformsangular-reactive-formsform-controlformgroups

Angular: how to create Form Controls from an array of objects


I can't seem to find a solution for this.

I have an array objects, lets say:

productInformation = {
   [
     {labelid: 1, labelname: 'weight', value: 1},
     {labelid: 2, labelname: 'height', value: 5},
     {labelid: 3, labelname: 'width', value: 10},
     {labelid: 4, labelname: 'depth', value: 2}
   ]
}

The objects will not always be predictable. Sometimes it'll have a only two objects, sometimes all of them, sometimes it'll have others, such as for color, condition, etc.

How can I create form controls with just the array of objects, where the admin can edit the values for each property (except for the id)? For example, the admin might want to update how much something weighs.

Each time I view a product's details, it will fetch an array of objects, as shown above.

Thank you.


Solution

  • Use addControl

      createGroup(productInformation:any[]):FormGroup{
        const form=new FormGroup({})
        productInformation.forEach(x=>{
           form.addControl(x.labelname,new FormControl(x.value))
        })
        return form
      }
    
    
    //you use
    this.form=this.createGroup(this.productInformation)
    

    To manange in .html you should create a function that return a formControl

      getControl(key:string)
      {
        return this.form.get(key) as FormControl
      }
    

    And use in html

    <form [formGroup]="form">
      <div *ngFor="let keyvalue of form.controls | keyvalue;let i=index">
        {{ productInformation[i].labelname }}
        <input [formControl]="getControl(productInformation[i].labelname)" />
      </div>
    </form>
    

    NOTE: you defined wrong the productInformation (remove the { }

    See a stacktblitz