I am creating form fields dynamically with ngFor and each field is having unique name attr. I am struggling in their validation.
My sample code:
<div *ngFor="let dimension of lstShippingDimensions; let i = index" class="dimension-item">
<input type="text" name="units-{{i}}" [(ngModel)]="dimension.units"
class="first-f" placeholder="# of units" required>
<input type="text" name="width-{{i}}" [(ngModel)]="dimension.width"
class="second-f" placeholder="W" required>
<input type="text" name="height-{{i}}" [(ngModel)]="dimension.height"
class="third-f" placeholder="H" required>
<input type="text" name="length-{{i}}" [(ngModel)]="dimension.length"
class="forth-f" placeholder="L" required>
<select class="five-f" name="unitType-{{i}}" [(ngModel)]="dimension.unitType"
required>
<option>inches</option>
<option>feet</option>
</select>
<div *ngIf="!units-{{i}}.valid && units-{{i}}.touched" class="text-danger text-left">
<small *ngIf="units-{{i}}.errors.required">Field is required.</small>
</div>
</div>
somehow resolved this with just adding #units="ngModel". I guess Angular is handling the referencing in ngFor itself. This works perfectly fine:
<div *ngFor="let dimension of lstShippingDimensions; let i = index" class="dimension-item">
<input type="text" name="units-{{i}}" #units="ngModel" [(ngModel)]="dimension.units" class="first-f" placeholder="# of units" required>
<input type="text" name="width-{{i}}" [(ngModel)]="dimension.width" class="second-f" placeholder="W" required>
<input type="text" name="height-{{i}}" [(ngModel)]="dimension.height" class="third-f" placeholder="H" required>
<input type="text" name="length-{{i}}" [(ngModel)]="dimension.length" class="forth-f" placeholder="L" required>
<select class="five-f" name="unitType-{{i}}" [(ngModel)]="dimension.unitType" required>
<option>inches</option>
<option>feet</option>
</select>
<div *ngIf="!units.valid && units.touched" class="text-danger text-left">
<small># of units is required.</small>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With