Angular For Loop Example

By Arvind Rai, February 11, 2024
This page will walk through Angular for loop Example with NgFor directive. 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> 
In the above code snippet, we are iterating users array using NgFor.
NgFor with component element is used as follows.
<emp-app *ngFor="let user of users" [emp]="user"> </emp-app> 
In the above code snippet, component property binding is taking place for each element in iteration. Now we will discuss complete example of NgFor here on this page step by step using TypeScript.

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) { 
  }
} 
user.component.ts
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)
    ];
} 
A good feature of 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 discuss NgFor 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>  
We need to add asterisk (*) as prefix with 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  
Now find the another way to use NgFor i.e using template directive.
<li template = "ngFor let user of users; let i = index">
  Row {{i}} : {{user.name}} - {{user.age}}
</li>  
Find the output.
Row 0 : Mahesh - 20
Row 1 : Krishna - 22
Row 2 : Narendra - 30  
In case we do not want to use asterisk(*), we can use 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>  
let-user and let-i : Using prefix let-, we declare variable. Here 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>  
Find the output.
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> 
Find the output.
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> 
Find the output.
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 of NgFor 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.

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; 
}
We will use NgFor with component property binding in user.component.html as follows.
<emp-app *ngFor="let user of users" [emp]="user"> </emp-app> 
For each and every elements of 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> 
Find *ngFor transformation into template.
1. First angular expands *ngFor into template directive.
<emp-app template="ngFor let user of users" [emp]="user"> </emp-app> 
It is up to our choice to use template directive in our code in place of *

2. Then angular expands template directive into <template> tag
<template ngFor let-user [ngForOf]="users">
  <emp-app [emp]="user"></emp-app>
</template> 
It is up to our choice to use <template> tag in our code in place of *

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 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> 

Output

Find the print-screen of the output.
Angular For Loop Example

References

NgFor DIRECTIVE
Template Syntax: NgFor

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us