This article will show how to use ngFor with index as value in Attribute in Angular.
The ngFor
directive in Angular is a powerful tool for rendering a list of items in your template. This tutorial will guide you on how to use the index
value within ngFor
in different versions of Angular. Understanding this concept is crucial for scenarios where you need to keep track of the position of each item in a list.
Angular Version 5+
Syntax
In Angular 5 and later versions, you can directly alias the index to a variable.
<ul> <li *ngFor="let item of items; index as i"> {{i+1}} {{item}} </li> </ul>
Setting Index in an Attribute:
You can also set the index value into an attribute of the HTML element.
<ul> <li *ngFor="let item of items; index as i" [attr.data-index]="i"> {{item}} </li> </ul>
Angular 2-4
Syntax
In these versions, the let
keyword is used to declare the index variable.
<ul> <li *ngFor="let item of items; let i = index" [attr.data-index]="i"> {{item}} </li> </ul>
AngularJS
AngularJS also follows a similar pattern, using the #
symbol to declare the index variable.
<ul> <li *ngFor="#item of items; #i = index" [attr.data-index]="i"> {{item}} </li> </ul>
Special Cases
Here are some special cases provided below.
Last Item in the List:
If you need to identify the last item in a list, use the last
keyword.
<div *ngFor="let item of devcaseFeedback.reviewItems; let last = last"> <divider *ngIf="!last"></divider> </div>
Other ngFor
Exported Values:
$implicit
: The value of the individual items in the iterable.ngForOf
: The iterable expression value.index
: The index of the current item.count
: The length of the iterable.first
:true
when the item is the first in the iterable.last
:true
when the item is the last in the iterable.even
:true
when the item index is even.odd
:true
when the item index is odd.
Practical Examples
Now, have a look at the practical examples below.
Example 1: Using index as i
<!-- app.component.html --> <h2 style="color: green">Example</h2> <h2>ngFor with index as value in attribute</h2> <div *ngFor="let item of items; index as i"> <b style="color: green;">{{i+1}} </b> <b>{{item}}</b> </div>
Example 2: Using let i=index
<!-- app.component.html --> <h2 style="color: green">Example</h2> <h2>ngFor with index as value in attribute</h2> <div *ngFor="let item of items; let i=index"> <b style="color: green;">{{i+1}} </b> <b>{{item}}</b> </div>
Conclusion
Understanding how to use the index within the ngFor
directive in Angular is essential for controlling the rendering of list items, especially when the position of each item is important in your application’s UI. This tutorial has covered the usage in different versions of Angular, allowing you to implement it effectively in your projects.