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.
.get(['banks', i, 'bankName'])whereiis index plnkr.co/edit/BWrz6tTe9Smo2UR3pyIz?p=preview