How to give formControlName to a FormArray object - Angular 2 (ReactiveFormsModule)

Dalvik picture Dalvik · Jun 22, 2017 · Viewed 20.1k times · Source

In my application I made a form using Reactive Forms. In my app their is a button Add new Fields upon clicking this button new fields are added.

I am able to add new fields but I am not able to assign formControlName.

Could any one please show me the right path how can I add formControlName to these dynamically added fields.

Here is the Plnkr for this.

Answer

yurzui picture yurzui · Jun 22, 2017

You have formArray of array of FormGroup.

So use formArrayName with loop of formGroupName with formControlName(itemDetail, quantity, rate...)

<table formArrayName="salesList">
    <tr>
     <th>Item Detail</th>
     <th>Quantity</th>
     <th>Rate</th>
     <th>Tax</th>
     <th>Amount</th>
    </tr>
    <!--Input controls -->
    <tr  *ngFor="let saleList of salesListArray.controls;let i = index" [formGroupName]="i">
        <td>
             <div class="col-sm-6">
                 <input class="form-control" type="text" placeholder="Item Detail" formControlName = "itemDetail"/>
             </div>
        </td>
         <td>
             <div class="col-sm-6">
                 <input class="form-control" type="text"   placeholder="0" formControlName = "quantity" />
             </div>
        </td>
         <td>
             <div class="col-sm-6">
                 <input class="form-control" type="text"   placeholder="0.00" formControlName = "rate"/>
             </div>
        </td>
         <td>
             <div class="col-sm-6">
                 <input class="form-control" type="text"   placeholder="Select a tax" formControlName = "tax"/>
             </div>
        </td>
         <td>
             <div class="col-sm-6">
                <span>{{saleList.amount}}}</span>
             </div>
        </td>
    </tr>
</table>

Fixed Plunker

See also