Angular: Get current index in ngFor

As per OP’s comment on question :

So, I am trying to get the index of the ngFor in order to do a comparison to array of data before triggering another function. For example, the test() function will be triggered when I click a button, then it will check the current index, and do something with it.

You should do it like :

<div class="test" *ngFor="let item of data; let i = index">
    // In your case this line should be within ngFor loop
    <div class="function_div" (click)="test(i);">Test Button </div>
    {{item}}
</div>

Note : Never call function like :

{{ test(i) }} // this will be executed each time anything changes in loop

Leave a Comment