17

I have following angular:

<div class="test" *ngFor="let item of data; let i = index">
    {{item}}
</div>

<div class="function_div" (click)="test(i);">Test Button </div>

then in .ts,

export class test{
   
  test(){
     console.log(i);
  }
  
}

I want to get a variable with the current index number.

How would I go about so that I can get the current index?

Thanks

ccpizza
  • 28,968
  • 18
  • 162
  • 169
Steve Kim
  • 5,293
  • 16
  • 54
  • 99
  • 2
    Where are you going to get index? What is the current index outside `ngFor` scope in your opinion? – yurzui Mar 06 '18 at 05:22
  • here is your answer https://stackoverflow.com/questions/36322829/how-to-use-track-by-inside-ngfor-angular-2 – Pavan Sikarwar Mar 06 '18 at 05:25
  • 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. – Steve Kim Mar 06 '18 at 05:26
  • 1
    There is no "current" index unless you call from within the `
    `. Outside of that div, your "loop" is complete, you just have the `data` array.
    – Roddy of the Frozen Peas Mar 06 '18 at 05:27
  • I see. Thank you. I understand. – Steve Kim Mar 06 '18 at 05:28
  • @steveKim , please also read the note on my answer :) – Vivek Doshi Mar 06 '18 at 05:32

4 Answers4

39

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

ccpizza
  • 28,968
  • 18
  • 162
  • 169
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
6

You couls alwasy go the simple way, like that:

    <div *ngFor =" let item of items; let i = index">

          {{ i }} {{ item }}

    </div>
Kobis
  • 61
  • 1
  • 3
4

Why you just not..

<div class="test" *ngFor="let item of data; let i = index">
    {{ test(i) }}
</div>


export class test{

  test(i: number){
     console.log(i);
  }

}
Kenry Sanchez
  • 1,703
  • 2
  • 18
  • 24
1

You can create your own directive to get the current index on every function call through *ngFor. You can follow this answer.

Ali Shahzad
  • 5,163
  • 7
  • 36
  • 64