It is one of the very common tasks in any of the language or its library/frameworks. In this article, We will see how to display array list items using the ngFor directive in the Angular framework.
Displaying Array list item using ngFor directive
Syntax
<tr *ngFor="let post of posts; let i = index">
..
..
<tr/>
Example
Let's say we have to show the below array item over the template. For simplicity, I am creating an array named posts with static items but in the real application, data may be dynamic and will be fetched for any server.
[
{
"userId": 1,
"id": 1,
"title": "Test title 1",
"body": "Test body1, This is test body"
},
{
"userId": 1,
"id": 2,
"title": "Test title 2",
"body": "Test body1, This is test body"
},
{
"userId": 1,
"id": 3,
"title": "Test title 3",
"body": "Test body1, This is test body"
},
{
"userId": 1,
"id": 4,
"title": "Test title 4",
"body": "Test body1, This is test body"
}
]
We will bind the above array into the template part. Here we will show it inside a table. Let's have a look at the code on the template side.
<table class="table table-dark">
<tr>
<th>Id</th>
<th>Title</th>
<th>Body</th>
<th>User Id</th>
</tr>
<tr *ngFor="let post of posts; let i = index">
<td>{{post.id}}</td>
<td>{{post.title}}</td>
<td>{{post.body}}</td>
<td>{{post.userId}}</td>
</tr>
</table>
In the above example, We have created a posts array inside a component ts file which is having objects in it with few properties like id, title, body, and userId. And bound that array items in angular template part.
The ngFor built-in structural directive of Angular provides a couple of local variables, Which can be used for performing some basic tasks while iteration of the array,
- Index: number – Used for getting the index for current element while iteration.
- First: boolean – It returns true if the current element is the first element in the iteration otherwise it returns false.
- Last: boolean – It returns true if the current element is the last element in the iteration otherwise it returns false.
- Even: boolean – IT returns true if the current element is even element based on the index in the iteration otherwise it returns false.
- Odd: boolean – It returns true if the current element is odd element based on the index in the iteration otherwise it returns false.
Let me know your thoughts over email at pankaj.itdeveloper@gmail.com. I would love to hear them and If you like this article, share it with your friends.
Thanks!