Learning2Code
Learning2Code

Reputation: 521

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>

Upvotes: 5

Views: 4490

Answers (2)

AVJT82
AVJT82

Reputation: 73367

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

Upvotes: 9

Garth Mason
Garth Mason

Reputation: 8011

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>

Upvotes: 1

Related Questions