0

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.

3
  • Does this answer your question? how to setvalue in formbuilder array Commented Jul 28, 2022 at 1:52
  • It didn't, but thank you Commented Jul 28, 2022 at 3:16
  • that is not a valid object Commented Jul 28, 2022 at 6:13

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I got the idea that I can do this, but wasn't sure if this would be good practice.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.