Search code examples
angularangular2-templatengforangular-validation

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>

Solution

  • 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