0

I am building dynamic input fields with a mandatory check inside ngFor. I have built names using field{{idxVar}} where idxVar is index but how do I use this for checking error

<span [ngClass]="{'active' : field{{idxVar}}.errors}">*Mandatory</span>
<input type="text" [required]="itmVar.is_required ? 'required' : null" name="field{{idxVar}}" [(ngModel)]="user.customFields[idxVar]"
            #field{{idxVar}}="ngModel">

In above, I know this is not the right method which gives error but want to know the right syntax for this

'active' : field{{idxVar}}.errors
1

2 Answers 2

1

For NgModel inside *ngFor, you can use unique template reference variable. Each input field is associated to the corresponding template reference, array index is not required.

<div *ngFor="let idxVar of valueArray">
  <span [ngClass]="{'active' : field.errors}">*Mandatory</span>
    <input type="text" name="field{{idxVar}}" [ngModel]="valueArray[idxVar]"
                #field="ngModel" (ngModelChange)="callback(field)">
    <div>{{ field.control.errors | json }}</div>
</div>

Here is the stackblitz code https://stackblitz.com/edit/angular-a4skhz

Sign up to request clarification or add additional context in comments.

Comments

0

It's not completely clear what you are trying to do but it seems what would work best for you would be to create an object fields with keys of numbers, corresponding to the indices you want to check on.

In your controller, have a fields object.

Then your template code would become something like

<span [ngClass]="{'active' : field[idxVar].errors}">*Mandatory</span>
<input type="text" [required]="itmVar.is_required ? 'required' : null" name="field[idxVar]" [(ngModel)]="user.customFields[idxVar]">

Here's a quick example in Stackblitz https://stackblitz.com/edit/angular-p4zemy

If this answer satisfies your needs, please be sure to mark it as accepted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.