Angular 10 Tutorial - ngFor Directive

In this tutorial, we will learn about the ngFor Directive in Angular 10. NgFor is a built-in template directive that makes it easy to iterate over an array or an object and create a template for each item.

Using ngFor Directive in Angular 10

So, let's see how we can use the ngFor Directive in Angular 10. Switch to the project and open the app.component.ts file. Here, let's create an array:


fruits = ['mango','orange','apple',' pineapple','banana '];

Now, add some elements to the array. To get each element of the array, go to the app.component.html file and write:


<ul>
<li *ngFor="let fruit of fruits">{{fruit}}</li>
</ul>

Now, let's check it. You can see the list of all fruits. Now, let's see the ngFor with an object array. Go to the app.component.ts file and create an object array:


users =[
{
name:'Alice',
email:'alice@gmail.com',
phone:'3530000012'
},
{
name:'Andrew',
email:'andrew@gmail.com',
phone:'3530000013'
},
{
name:'Mike',
email:'mike@gmail.com',
phone:'3530000014'
},
{
name:'Sophie',
email:'sophie@gmail.com',
phone:'3530000015'
},
{
name:'Steve',
email:'steve@gmail.com',
phone:'3530000016'
}
];

Now, get each user by ngFor directives. Go to the app.component.html file and add a table:


<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of users">
<td>{{user.name}}</td>
<td>{{user.email}}</td>
<td>{{user.phone}}</td>
</tr>
</tbody>
</table>

Now, let's check it. Switch to the browser and you can see the names, emails, and phone numbers.

So, in this way, you can use ngFor Directives in Angular 10.