Angular - List elements References
While handling a list in angular, we may sometimes need to identify some common references, like index, first, last, even, odd, etc.,
Let's see how we can use such references within the angular code.
Using index
Use the reference index
to get the index of the element in the list, which starts with 0 for the first list element.
The index value is a number starting from 0 for the first list element.
<ul>
<li *ngFor="let item of posts; let index = index">{{item.title}} - {{index}}</li>
</ul>
Using the first and last
Use the references first
and last
to distinguish the first and last elements of a list from other elements.
The value of these references is a boolean value, either true or false.
<ul>
<li *ngFor="let item of posts; let first = first; let last = last;">
<p *ngIf="first">First Element: {{item.title}}</p>
<p *ngIf="!first && !last">Other Element: {{item.title}}</p>
<p *ngIf="last">Last Element: {{item.title}}</p>
</li>
</ul>
Using the even and odd
Use the references even
and odd
to distinguish the even and odd indexed elements of a list from other elements.
The value of these references is a boolean value, either true or false.
<ul>
<li *ngFor="let item of posts; let even = even; let odd = odd;">
<p *ngIf="even">Even Element: {{item.title}}</p>
<p *ngIf="odd">Odd Element: {{item.title}}</p>
</li>
</ul>
Conclusion
Now, we know how to use the list element references in an angular list.