In Angular Version 17+ using built in control flow:
<ul>
@for (item of items; track item; let i = $index) {
<li>
{{i+1}} {{item}}
</li>
}
</ul>
In Angular Version 5+:
<ul>
<li *ngFor="let item of items; index as i">
{{i+1}} {{item}}
</li>
</ul>
I would use this syntax to set the index value into an attribute of the HTML element:
Angular 2-4
You have to use let to declare the value rather than #.
<ul>
<li *ngFor="let item of items; let i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
AngularJS
<ul>
<li *ngFor="#item of items; #i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.
Answer from Thierry Templier on Stack OverflowIn Angular Version 17+ using built in control flow:
<ul>
@for (item of items; track item; let i = $index) {
<li>
{{i+1}} {{item}}
</li>
}
</ul>
In Angular Version 5+:
<ul>
<li *ngFor="let item of items; index as i">
{{i+1}} {{item}}
</li>
</ul>
I would use this syntax to set the index value into an attribute of the HTML element:
Angular 2-4
You have to use let to declare the value rather than #.
<ul>
<li *ngFor="let item of items; let i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
AngularJS
<ul>
<li *ngFor="#item of items; #i = index" [attr.data-index]="i">
{{item}}
</li>
</ul>
Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.
In Angular 5/6/7/8:
<ul>
<li *ngFor="let item of items; index as i">
{{i+1}} {{item}}
</li>
</ul>
In older versions
<ul *ngFor="let item of items; let i = index">
<li>{{i+1}} {{item}}</li>
</ul>
Angular.io โธ API โธ NgForOf
- Description
- Local variables
Unit test examples
- ng_for_spec.ts
Another interesting example
- Grouping
Videos
I have a div like this hosted by an Angular component. I want to pass the value of the index to a component property so I did this
<div *ngFor='let key of [1,2,3]; let i = index' >
{{ test(i) }}
</div>and test() is defined as
test(i: number)
{
this.cgindex = i;
console.log(`i = ${i}`);
if (i == 0)
this.count += 1;
console.log(`count = ${this.count}`);
}cgindex is the component property I am setting. The property is used to do some calculations for every loop iteration.
A couple of questions:
1- Is there a better way to update the property value? I don't like this method call of setting the value.
2- I noticed every time I clicked on the page, logging happens. My guess Angular is revaluating everything with every mouse click and calling test() multiple times. That's why I don't like this implementation.