Rahul
Rahul

Reputation: 5834

How to access control in HTML defined inside FormArray in component - Angular2

I am using ReactiveFroms in my app. When I added static controls then every thing is working fine. I am showing validation errors using inbuilt classes of controls. Working Plunkr with static controls.

But when I try to add dynamic controls then I am not able to access controls in order to apply inbuilt validation.

I am facing problem in accessing control reference from HTML template in order to apply validation. I am not able to figure it out how can I access controls. Here is the plunkr for that.

Here is my template for adding dynamic controls:

  <form [formGroup]="valForm" class="form-validate form-horizontal"  >
<div formArrayName="banks">
     <div *ngFor="let bank of bankArray.controls;let i = index" [formGroupName]="i">
        <legend>Bank Details</legend>
    <fieldset>
        <div class="form-group">
            <label class="col-sm-2 control-label">Name of the Bank</label>
            <div class="col-sm-6">
                <input class="form-control " type="text" placeholder="Enter Bank Name" formControlName="bankName" [formControl]="valForm.controls['banks']" />
                <span class="text-danger" *ngIf="valForm.controls['bankName'].hasError('required') && (valForm.controls['bankName'].dirty || valForm.controls['bankName'].touched)">This field is required</span>
            </div>
        </div>
    </fieldset>
    </div>
 </div>
 <button (click)="addNewBank()">Add New Bank</button>
 </form>

I am not able to figure it out how I can access formControl in order to add validations. I tried various approach like:

       valForm.controls['banks'][bankName]; //Not working
       valForm.controls['banks'][0][bankName] //Not working

         <input class="form-control " type="text" placeholder="Enter Bank Name" formControlName="bankName" [formControl]="valForm.get('bankName')" />
                <span class="text-danger" *ngIf="valForm.controls['bankName'].hasError('required') && (valForm.get('bankName').dirty || valForm.get('bankName').touched)">This field is required</span> //Not working

Here is the plunker for that.

Upvotes: 2

Views: 3711

Answers (1)

yurzui
yurzui

Reputation: 214017

I see several options

valForm.get(['banks', i, 'bankName'])
valForm.get('banks.' + 'i' + '.bankName')

bankArray.get([i, 'bankName'])
bankArray.get(i + '.bankName')

bankArray.at(i).get('bankName')

Upvotes: 4

Related Questions