How to get the ngFor index value

Asked

Viewed 23,929 times

6

Could help me in a doubt, I have a form with an array where there is the FormControl "id". Is there any way to receive the value of index to fill in this field?

<tr *ngFor="let item of invForm.controls.tool.controls; let i= index" [formGroupName]="i" >
    <td>
        <mat-form-field floatLabel='never'>
            <input matInput type="number" style="text-align: right" formControlName="Id"  value="{{i+1}}"  >
        </mat-form-field>
    </td>
</tr>

I made this example in stackblitz.

[Solved]

I solved the problem with the trackBy: trackByFn

<tr *ngFor="let item of invForm.controls.tool.controls; let i= index ;trackBy: trackByFn" [formGroupName]="i"  >

and in the component,

 trackByFn(index, item) {

     item.value.Id = index+1
    return index; 
  } 

I also leave the resolution on stackblitz

1 answer

20

  • Thank you for your reply, but I have tried these methods and they have not worked

  • Try the yes I tested it right here. Post your html

  • Create the index and show it in the right item, but I want to pass this index to the FormControl. I’ll try to use the trackBy: trackByFn.

  • Put your Formcontrol ? where you want to pass!

  • This will not work as it wishes to apply the value of i to the form field ID. What you are doing is displaying on the screen, which is not what the author wants to do.

  • That’s what Celso said, I needed to pass the index value i for the ID form. The example is here https://stackblitz.com/edit/invoice-id

  • vc wants to take the index of the array of elements in your . ts ?

  • Thanks for the @LR10 layout, I decided with the trackBy: trackByFn even

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.