Angular 2 checking for dynamically generated fields in a loop
I have a list of input fields that are generated using a model. I am trying to add confirmation to them. Requirement must not be empty or less than 2 characters. the problem in the documentation only shows validation with the non-dynamically generated variable Name. My fields are dynamically generated. So there is no tempVariableName that I can hardcode (otherwise they conflict), so I created a temporary variable from the name of the property that I bound the field to. So I came up with something like this:
<div *ngFor="let field of connector.configFields">
<label>{{field.name}}</label>
<input [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'"
placeholder="{{field.name}} (required)"
ngControl="[fieldName+field.name]"
required minlength="2"
#fieldName+[field.name]="ngModel" />
<div *ngIf="(fieldName+[field.name]).errors && ((fieldName+[field.name]).dirty || (fieldName+[field.name]).touched)">
<span *ngIf="(fieldName+[field.name]).errors.required">Enter Name</span>
<span *ngIf="(fieldName+[field.name]).errors.minlength">Name minimum at 2 characters</span>
</div>
</div>
and configFields in typescript look like this:
export class FieldModel {
public name: string;
public type: string;
public value: any;
}
But it just won't work. I'm new to angular 2, so I'm not really sure what I did wrong.
source to share
You can use unique index
for each field in the array. Use this in conjunction with the attribute name
(s ngModel
), which will evaluate each control separately. Therefore, each input field is given a unique name, for example:
name="f{{i}}"
where we get {{i}}
from iteration:
<div *ngFor="let field of connector.configFields; let i = index">
So your template might look like this:
<form #myForm="ngForm">
<div *ngFor="let field of connector.configFields; let i = index">
<input name="f{{i}}" [(ngModel)]="field.value" [type]="field.name === 'Password' ? 'password' : 'text'" required #f="ngModel" minlength="2"/>
<div *ngIf="f.errors && (f.dirty || f.touched)">
<div *ngIf="f.errors.required"> This field is required </div>
<div *ngIf="f.errors.minlength"> Min 2 chars </div>
</div>
</div>
</form>
Here live
Demo
source to share