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
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.
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.
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
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);
}
}
You couls alwasy go the simple way, like that:
<div *ngFor =" let item of items; let i = index">
{{ i }} {{ item }}
</div>
You can create your own directive to get the current index on every function call through *ngFor
. You can follow this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With