Home > Software design >  Angular: how to create Form Controls from an array of objects
Angular: how to create Form Controls from an array of objects

Time:07-28

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.

CodePudding user response:

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

CodePudding user response:

Something like this should work:

product: FormGroup;

constructor(private fb: FormBuilder) {
 this.product.addControl('productInformation', new FormArray([]));
}

setInformation(productInformation){
  const options = this.product.get('productInformation') as FormArray;
  for(let {labelid, labelname, value} of productInformation){
    options.push(this.fb.group({ labelid, labelname, value } as any));
  }
}

You can set labelid without using an input by setValue or patchValue.

  • Related