How can I refer to a control added to ngFor?
I am adding multiple inputs using ngFor on a form with a template, and I would like to add appropriate error messages if the inputs are invalid. Usually, if I didn't use ngFor, I would use # inputName = "ngModel". Is there a way for me to do something like this to reference the dynamically added input?
Basically I want to do something like this:
<div *ngFor="let field of fields; let i = index">
<label>{{field.label}}</label> <input [ngModel]="field.value" required #field{{i}}="ngModel" />
<div *ngIf="field{{i}}.invalid"> This field is required </div>
</div>
+3
source to share
2 answers
garth74's answer is almost correct. In forms, the attribute name
must be unique so that in your case each input field is recognized as a separate form control. So here use an index to assign a unique name:
name="f{{i}}"
... so your code will look like this:
<div *ngFor="let field of fields; let i = index">
<label>{{field.label}}</label> <input name="f{{i}}" [ngModel]="field.value" required #f="ngModel" />
<div *ngIf="f.invalid"> This field is required </div>
</div>
Here a
DEMO
+6
source to share
You don't need to do anything to reference this field in the template - just use the alias directly (eg "f")
<div *ngFor="let field of fields; let i = index">
<label>{{field.label}}</label> <input [ngModel]="field.value" required #f="ngModel" />
<div *ngIf="f.invalid"> This field is required </div>
</div>
+1
source to share