Angular: Get current index in ngFor

后端 未结 4 1175
失恋的感觉
失恋的感觉 2021-01-04 12:05

I have following angular:

{{item}}
相关标签:
4条回答
  • 2021-01-04 12:30

    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

    0 讨论(0)
  • 2021-01-04 12:40

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

    0 讨论(0)
  • 2021-01-04 12:45

    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);
      }
    
    }
    
    0 讨论(0)
  • 2021-01-04 12:50

    You couls alwasy go the simple way, like that:

        <div *ngFor =" let item of items; let i = index">
    
              {{ i }} {{ item }}
    
        </div>
    
    0 讨论(0)
提交回复
热议问题