AlexanderM
AlexanderM

Reputation: 1683

angular 4 add grid controls to formGroup

I am having a grid where one of the columns is the input box. I want all of these input boxes be a part of the same form group. How can I achieve that?

My is something like:

    <form [formGroup]="pricesFormGroup">

        <table>
            <tbody>
                <tr *ngFor="let product of products">
                    <td>
                        {{product.productName}}
                    </td>

                    <td>
                        <!--This is control I need to add to my formgroup-->
                        <input type="text"
                                [(ngModel)]="product.Price"
                                required>                                   
                    </td>
                </tr>
            </tbody>
        </table>
    </form>

Upvotes: 1

Views: 1036

Answers (1)

AVJT82
AVJT82

Reputation: 73367

If you'd want to have just that one value, I would do some preparation and make the formgroup as such, that you can directly display it in template and ignore products array completely. Here in this sample I set product.name as the property name, and product.Price as the value:

iterable = []; // store formgroup object keys to be displayed in template
pricesFormGroup: FormGroup;

constructor(private fb: FormBuilder) {
  this.pricesFormGroup = this.fb.group({});
  this.populateForm();
 }

populateForm() {
  this.products.forEach(x => {
    this.pricesFormGroup.addControl(x.productName, new FormControl(x.Price))
  })
  this.iterable = Object.keys(this.pricesFormGroup.value)
}

and template:

<form [formGroup]="pricesFormGroup">
  <div *ngFor="let pro of iterable">
    <p>{{pro}}</p>
    <input [formControlName]="pro">
  </div>
</form>

This would produce..

{
  myProductName1: myProduct1_price
  // ...
}

Please ignore my poor naming conventions :D

DEMO

Upvotes: 3

Related Questions