Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Get current index in ngFor

Tags:

angular

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

like image 640
Steve Kim Avatar asked Mar 06 '18 05:03

Steve Kim


People also ask

Which of the following is the correct syntax for getting index using * ngFor?

The syntax is *ngFor="let <value> of <collection>" . <value> is a variable name of your choosing, <collection> is a property on your component which holds a collection, usually an array but anything that can be iterated over in a for-of loop.

What is TrackBy in ngFor Angular?

TrackBy is used to track the latest value in the dom without refreshing the full dom element. It only updates the new data. Prerequisites. Basic knowledge of Angular. Visual Studio Code must be installed.


4 Answers

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

like image 187
Vivek Doshi Avatar answered Oct 16 '22 19:10

Vivek Doshi


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);
  }

}
like image 31
Kenry Sanchez Avatar answered Oct 16 '22 19:10

Kenry Sanchez


You couls alwasy go the simple way, like that:

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

          {{ i }} {{ item }}

    </div>
like image 5
Kobis Avatar answered Oct 16 '22 18:10

Kobis


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

like image 1
Ali Shahzad Avatar answered Oct 16 '22 17:10

Ali Shahzad