Angular 2 NgFor Example
November 12, 2016
This page will walk through angular 2 NgFor example. NgFor is a directive that iterates over collection of data. It is used to customize data display. Whenever there is change in collection of data at runtime, that will be updated in data display iterated by NgFor
directive. NgFor
provides local variables that will help to get index of current iteration, detect if element in iteration is first or last and odd or even. NgFor
is used with HTML element as well as component element. NgFor
with HTML element iterates the template within it. NgFor
with component element iterates the child component HTML template. NgFor
can be used with asterisk(*) or template directive or template tag. Any change in contents in iteration is propagated to DOM.
NgFor
with HTML element is used as follows.
<div *ngFor="let user of users; let i = index"> Row {{i}} : {{user.name}} - {{user.age}} </div>
users
array using NgFor
. In angular 1.x, we iterate using ng-repeat
. In angular 2 NgFor
is the replacement of it.
NgFor
with component element is used as follows.
<emp-app *ngFor="let user of users" [emp]="user"> </emp-app>
NgFor
here on this page step by step using TypeScript.
Contents
- Software Used
- NgFor Local Variables
- Create Class, Component and HTML Template
- NgFor with HTML Elements
- NgFor with index
- NgFor with first and last
- NgFor with even and odd
- NgFor with Component Property Binding
- Expanding *ngFor into template
- NgFor Change Propagation
- Angular 4 NgForOf
- Other Files of Demo Application
- Run Application
- References
- Download Source Code
Software Used
Find the software used in our demo.1. Angular 2.3.0
2. TypeScript 2.0.10
3. Node.js 4.6.0
4. NPM 3.10.8
5. Firefox 50.1.0
NgFor Local Variables
NgFor
uses following local variables.
index: Provides the index for current loop iteration. Index starts from 0.
first: Provides Boolean value. It returns true if the element is first in the iteration otherwise false.
last: Provides Boolean value. It returns true if the element is last in the iteration otherwise false.
even: Provides Boolean value. For every index of elements in the iteration, if even then returns true otherwise false.
odd: Provides Boolean value. For every index of elements in the iteration, if odd then returns true otherwise false.
Create Class, Component and HTML Template
Find the typescript file and HTML template used in our example.user.ts
export class User { constructor(public name: string, public age: number) { } }
import {Component} from '@angular/core'; import {User} from './user'; @Component({ selector: 'user-app', templateUrl: 'app/user.component.html' }) export class UserComponent { users = [ new User('Mahesh', 20), new User('Krishna', 22), new User('Narendra', 30) ]; }
NgFor
is that whenever there is change in users
array at runtime, that will be updated in data display iterated by NgFor
. In our component we have array of User
class as users
. We will iterate this array using NgFor
. If a user is added or removed in users
array at runtime, that will be updated in display. If at any index in users
array, the instance of User
is updated then that will also be updated in display iterated by NgFor
. Now find the HTML template that will show how to iterate data using NgFor
.
user.component.html
<b> *ngFor Demo</b> <ul> <li *ngFor="let user of users"> {{user.name}} - {{user.age}} </li> </ul> <b> ngFor with template Attribute </b> <ul> <li template = "ngFor let user of users; let i = index"> Row {{i}} : {{user.name}} - {{user.age}} </li> </ul> <b> ngFor with template Tag </b> <ul> <template ngFor let-user [ngForOf] = "users" let-i = "index"> <li> Row {{i}} : {{user.name}} - {{user.age}} </li> </template> </ul> <b>index variable demo </b> <p *ngFor="let user of users; let i = index"> Row {{i}} : Name: {{user.name}} </p> <b>first and last variable demo </b> <div *ngFor="let user of users; let i = index; let f=first; let l=last;"> Row {{i}} : Name: {{user.name}}, is first row: {{f}}, is last row: {{l}} </div> <b>even and odd variable demo </b> <div *ngFor="let user of users; let i = index; let e=even; let o=odd;"> Row {{i}} : Name: {{user.name}}, is even row: {{e}}, is odd row: {{o}} </div> <br/><b>ngFor with component element using *ngFor</b> <emp-app *ngFor="let user of users" [emp]="user"> </emp-app> <br/><b>ngFor with component element using template directive </b> <emp-app template="ngFor let user of users" [emp]="user"> </emp-app> <br/><b>ngFor with component element using template tag </b> <template ngFor let-user [ngForOf]="users"> <emp-app [emp]="user"></emp-app> </template>
NgFor with HTML Elements
Here we will discussNgFor
with HTML elements. NgFor
directive is used with asterisk (*) and template directive as well as <template> tag. First find how to use NgFor
with asterisk (*).
<li *ngFor="let user of users"> {{user.name}} - {{user.age}} </li>
ngFor
as *ngFor
. Here users
is a collection of User
instances in our example. To define a variable we need to use let
keyword. We have defined here two variables user
and i
. For every iteration an element from users
collection is assigned to the variable user
which is accessed within the tag. Here index
returns the index of row while iteration. *ngFor
can be used with HTML tags such as <div>, <li>, <p> etc.
Find the output.
Mahesh - 20 Krishna - 22 Narendra - 30
NgFor
i.e using template
directive.
<li template = "ngFor let user of users; let i = index"> Row {{i}} : {{user.name}} - {{user.age}} </li>
Row 0 : Mahesh - 20 Row 1 : Krishna - 22 Row 2 : Narendra - 30
template
directive. We can also use <template>
tag for NgFor
as follows.
<template ngFor let-user [ngForOf] = "users" let-i = "index"> Row {{i}} : {{user.name}} - {{user.age}} </template>
user
and i
are variables.
[ngForOf] : [] is used to assign a source value into a target within any tag.
ngForOf
is the property of NgFor
class. In ngForOf
we assign our array to iterate.
Find the output.
Row 0 : Mahesh - 20 Row 1 : Krishna - 22 Row 2 : Narendra - 30
NgFor with index
index
gives the index for current loop iteration.
<p *ngFor="let user of users; let i = index"> Row {{i}} : Name: {{user.name}} </p>
Row 0 : Name: Mahesh Row 1 : Name: Krishna Row 2 : Name: Narendra
NgFor with first and last
first
and last
are Boolean values. first
returns true for the element of first iteration otherwise false. last
returns true for the element of last iteration otherwise false.
<div *ngFor="let user of users; let i = index; let f=first; let l=last;"> Row {{i}} : Name: {{user.name}}, is first row: {{f}}, is last row: {{l}} </div>
Row 0 : Name: Mahesh, is first row: true, is last row: false Row 1 : Name: Krishna, is first row: false, is last row: false Row 2 : Name: Narendra, is first row: false, is last row: true
NgFor with even and odd
even
and odd
are Boolean values. even
returns true for element if iteration number is even otherwise false. odd
returns true for element if iteration number is odd otherwise false.
<div *ngFor="let user of users; let i = index; let e=even; let o=odd;"> Row {{i}} : Name: {{user.name}}, is even row: {{e}}, is odd row: {{o}} </div>
Row 0 : Name: Mahesh, is even row: true, is odd row: false Row 1 : Name: Krishna, is even row: false, is odd row: true Row 2 : Name: Narendra, is even row: true, is odd row: false
NgFor with Component Property Binding
Here we will provide example ofNgFor
using component element in component property binding. We perform component property binding between two components. There will be a parent component and a child component. In component property binding we copy a component property value from parent to child component property. To read more about component property binding, go the link Angular 2 Property Binding Example.
Here in our example parent component is
user.component.ts
. Now we will create a child component as follows.
employee.component.ts
import {Component, Input} from '@angular/core'; import {User} from './user'; @Component({ selector: 'emp-app', template: ` <br/> {{emp.name}} - {{emp.age}} ` }) export class EmployeeComponent { @Input() emp : User; }
NgFor
with component property binding in user.component.html
as follows.
<emp-app *ngFor="let user of users" [emp]="user"> </emp-app>
users
, component element will execute child component. For every iteration the value of emp
will be assigned by user
. Output will be as given below.
Mahesh - 20 Krishna - 22 Narendra - 30
Expanding *ngFor into template
We will understand her how angular transform the*ngFor
into template. In our example we are using *ngFor
as given below.
<emp-app *ngFor="let user of users" [emp]="user"> </emp-app>
*ngFor
transformation into template.
1. First angular expands
*ngFor
into template directive.
<emp-app template="ngFor let user of users" [emp]="user"> </emp-app>
2. Then angular expands template directive into <template> tag
<template ngFor let-user [ngForOf]="users"> <emp-app [emp]="user"></emp-app> </template>
In all the three cases that is * and template directive and <template> tag, output will be the same.
NgFor Change Propagation
For any change in contents of iteration,NgFor
performs the corresponding changes to DOM. When a new element is added, new instance of template is added to DOM. When an element is removed, the corresponding template instance is also removed. If elements are reordered, then corresponding templates are also reordered in DOM. Angular uses object identity to track any changes in iterator and that is reproduced in DOM. In this way change propagation is performed. We can also customize default tracking algorithm by using trackBy
property. We can assign our function to trackBy
which will accept index
and item
.
Angular 4 NgForOf
NgForOf
directive is used with HTML elements as following.
<li *ngFor="let item of items; index as i; even as isEven; odd as isOdd; first as isFirst; last as isLast; trackBy: trackByFn"> ------ </li>
NgForOf
directive is used with <ng-template>
as following.
<ng-template ngFor let-item [ngForOf]="items" let-i="index" let-isEven="even" let-isOdd="odd" let-isFirst="first" let-isLast="last" [ngForTrackBy]="trackByFn"> <li> ------ </li> </ng-template>
Angular 4 ngFor Example
Other Files of Demo Application
Create Module, Main and index.html using TypeScript used in demo application.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { UserComponent } from './user.component'; import { EmployeeComponent } from './employee.component'; @NgModule({ imports: [BrowserModule], declarations: [UserComponent, EmployeeComponent], bootstrap: [UserComponent] }) export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import {AppModule} from './module'; const platform = platformBrowserDynamic(); platform.bootstrapModule(AppModule);
<html> <head> <title>Angular 2 Demo</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="node_modules/core-js/client/shim.min.js"></script> <script src="node_modules/zone.js/dist/zone.js"></script> <script src="node_modules/reflect-metadata/Reflect.js"></script> <script src="node_modules/systemjs/dist/system.src.js"></script> <!-- Configure SystemJS --> <script src="systemjs.config.js"></script> <script> System.import('myApp').catch(function(err){ console.error(err); }); </script> </head> <body> <user-app>Please Wait...</user-app> </body> </html>
Run Application
Find the steps to run the example.1. Install Node.js and NPM in the system if not already installed. Make sure that Node.js version must be 4.x.x or higher and NPM version must be 3.x.x or higher.
2. Download the source code using download link given below in the example.
3. Go to the root folder of the project using command prompt and run npm install command.
4. Now run npm start command.
5. Now run index.html file. Find the print screen of the output.

References
NgFor DIRECTIVETemplate Syntax: NgFor