Zakaria Nya
Zakaria Nya

Reputation: 43

Get index from template *ngfor for use in my typescript class

I'm trying to use the index of my *ngFor inside of my typescript class. Example :

*ngFor="let item of items; let i = index";

How can I send the index value (i) into the component controller ?

Upvotes: 2

Views: 835

Answers (2)

Antoine Delia
Antoine Delia

Reputation: 1845

You can get the index in your typescript code by sending it with an event. Take this for example:

<li *ngFor="let item of items; index as i" (click)="yourFunction(i)">
    {{item}}
</li>

When you click on the item, this will send your index to your typescript function.

yourfunction(i: number) {
    // Your code here
    alert(i);
}

More info about local variables can be found here.

Upvotes: 2

Andrew Howard
Andrew Howard

Reputation: 3092

Template:

<div *ngFor="let item of items; let i = index";>
<a (click)="sendInvoice(i)">Send</a>
</div>

TS:

sendInvoice(i){
console.log(i);
}

Upvotes: 2

Related Questions