Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reference control added in ngFor?

I am adding several inputs using ngFor in a template driven form and I would like to add corresponding error messages for when the inputs are invalid. Normally if I was not using ngFor I would use #inputName="ngModel". Is there any way for me to do something like this in order 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>
like image 904
Learning2Code Avatar asked Feb 04 '23 18:02

Learning2Code


2 Answers

garth74's answer is almost correct. In forms, the name attribute has to be unique, so that in your case, each input field is recognized as a separate form control. So here use the index to assign the unique name:

name="f{{i}}"

... so your code would then 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's a

DEMO

like image 94
AT82 Avatar answered Feb 15 '23 06:02

AT82


You shouldn't need to do anything special to reference that field in the template - just use an alias directly (e.g. '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>
like image 24
Garth Mason Avatar answered Feb 15 '23 06:02

Garth Mason