Here we will see how to iterate over an array using ngFor directive.
Use ngFor directive to display the records in the component's HTML template.
In Angular JS i.e., Angular version 1, ng repeat is used for iteration. Angular 2 and above uses ngFor built-in directive.
ngFor is a structural directive and should be used with an asterisk symbol. For example, if GET HttpMethod is used to fetch a list, ngFor can be used to iterate the list returned by the GET response. ngFor can be used with Iterables such as Arrays and can display the result in table format.
NgForComponent
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template:`
<h1>{{title}}</h1>
<ul *ngFor="let fruit of fruits">
<li>
{{fruit.id}} {{fruit.name}}
{{fruit.price}} {{fruit.quantity}}
</li>
</ul>
`,
styles: ['ul {list-style-type: square;}']
})
export class NgForComponent{
title = "Ng For Directive Example" ;
fruits: Fruit[] =[
{id:'1',name:'Apple',
price:'$10.00',quantity:'2'},
{id:'2',name:'Berries',
price:'$20.00',quantity:'2'},
{id:'3',name:'Cherry',
price:'$30.00',quantity:'1'},
{id:'4',name:'Dates',
price:'$40.00',quantity:'1'},
]
}
class Fruit{
id : string;
name : string;
price : string;
quantity : string;
}
fruit is the looping variable and fruits is the array. We are creating looping variable fruit for fruits array and passsing it as an expression to *ngFor directive. let keyword is used to declare a local variable fruit.
For each element in an array ngFor directive repeats the HTML template.
ngFor can be used with Iterables such as Arrays. If plain object need to be iterated it has to be first converted in to array using the following JavaScript Object methods,
Object.keys(object)
Object.values(object)
Object.entries(object)
This will be explained in detail in a later post.
*ngFor is a shorthand for ng-template ngFor. If ngFor is used with an asterisk symbol Angular will internally convert to ng-template syntax.
<ng-template ngFor
let-fruit
[ngForOf]="fruits">
{{fruit.id}}
</ng-template>
Replacing the component template with following code will also work in the same way,
template:`
<h1>{{title}}</h1>
<ng-template ngFor
let-fruit
[ngForOf]="fruits">
<ul>
<li>
{{fruit.id}}
{{fruit.name}}
{{fruit.price}}
{{fruit.quantity}}
</li>
</ul>
</ng-template>
`,