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>
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With