Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 548
Rahul Avatar asked Jun 22 '17 10:06

Rahul


1 Answers

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

  • https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2
  • https://angular.io/guide/reactive-forms#display-the-formarray
like image 185
yurzui Avatar answered Oct 21 '22 11:10

yurzui