Angular 6|7 ngFor Example

In this tutorial, you'll learn about the ngFor directive by example in Angular 6.

You'll learn about these concepts:

  • What's ngFor and what's used for,
  • How to use trackBy with ngFor,
  • How to get the index in ngFor

Let's get started started!

What ngFor is Used for?

ngFor is a directive that you can use in your Angular templates to loop through lists and arrays of data in order to display it.

Let's suppose we have an Angular 6 component that has the following array of data:

policies: [] = [
    {id: 0, name: "policy001"},
    {id: 2, name: "policy002"},
    {id: 3, name: "policy003"},
    {id: 4, name: "policy004"},
    {id: 5, name: "policy005"}, 
];

In your template, you can display your policies in HTML table using an ngFor directive. For example, this is an example template:

<table>
<thead>
<th># Policy ID</th>
<th>Policy name</th>
</thead>
<tbody>
<tr *ngFor="let policy of policies">
<td>{{policy.id}}</td>
<td>{{policy.name}}</td>
</tr>
</tbody>
</table>

This is the example of a complete Angular component with a template:

@Component({
    selector:'policy-list',
    template: `
<table>
<thead>
<th># Policy ID</th>
<th>Policy name</th>
</thead>
<tbody>
<tr *ngFor="let policy of policies">
<td>{{policy.id}}</td>
<td>{{policy.name}}</td>
</tr>
</tbody>
</table>
`   
})
export class PolicyListComponent {
    policies: [] = [
      {id: 0, name: "policy001"},
      {id: 2, name: "policy002"},
      {id: 3, name: "policy003"},
      {id: 4, name: "policy004"},
      {id: 5, name: "policy005"},   
    ];
}

You simply pass ngFor an expression in the let ELEMENT of YOUR_ARRAY. ELEMENT is a variable that refers to an item of the array and that's accessed inside the loop. YOUR_ARRAY refers to an array declared in the corresponding component.

The let and of keywords are mandatory in the ngFor expression.

How to Find the Index of the Current Element in the ngFor loop

In many scenarios, you would need to know about the index of the current element inside the ngFor loop.

You can simply use the index keyword. For example:

<tr *ngFor="let policy of policies; let i = index">
    <td>Index: {{i}}</td>
    <td>{{policy.name}}</td>
</tr>

As you can see, we simply add another expression— let i = index which assigns the index to the i variable.

Getting the First and Last Elements inside an ngFor loop

You also access the first and last elements of your ngFor loop using two first and last variables. For example:

<tr *ngFor="let policy of policies; let first = first; let last = last">
    <td></td>
</tr> 

For example, you can use these variables to apply different CSS styles to the first and last elements.


Author


SUBSCRIBE


JOIN OUR COMMUNITY!


comments powered by Disqus