14

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.

user93
  • 1,866
  • 5
  • 26
  • 45
Rahul
  • 5,594
  • 7
  • 38
  • 92

1 Answers1

15

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

yurzui
  • 205,937
  • 32
  • 433
  • 399
  • thanks it is working now. I searched but I havent found any info about how to use formArrayName like this.If possible could you please provide me any link from which I can Learn in detail. – Rahul Jun 22 '17 at 11:14
  • Plunker link never loads for me :( – Crystal Sep 25 '19 at 19:09
  • @Crystal I've updated the link https://plnkr.co/edit/jdFnKtwb1lRPMERllSMR?p=preview – yurzui Sep 25 '19 at 19:18
  • For anyone using `mat-table`, use [this answer](https://stackoverflow.com/a/51348069/64279) to get the index. – adam0101 Sep 25 '20 at 13:22