Sat, Mar 14, 2020
Read in 2 minutes
How to use *ngFor :
*ngFor directive is used to loop and iterate each item of an array . It is like “for-loop” in any programming language.
app.component.ts
Let’s declare a “testarray ” with default values like below.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ngforDemo';
testarray = [
{
name: 'Bob',
age: 32,
},
{
name: 'Kate',
age: 42,
},
{
name: 'Raviga',
age: 42,
},
{
name: 'Tom',
age: 42,
},
{
name: 'Evana',
age: 32,
}
]
}
app.component.html In the Template , you can iterate the “testarray” using *ngFor directive.To know the know declare i=index;
<div *ngFor="let element of testarray;let i=index;">
array index = {{i}},
{{element.name}}
{{element.age}}
</div>
To find the length of the array:
<p> length of the array !!::: {{testarray.length}} </p>
###OUTPUT To apply a specific style to First and last elements:
<ul>
<li
*ngFor="let element of testarray; let first = first; let last = last"
[ngClass]="{ first: first, last: last }">
{{element.name}} {{element.age}}
</li>
</ul>
.first{
color: blue;
font-weight: bold;
}
.last{
color: brown;
font-weight: bold;
}
To find odd and even elements of the array
<p>print odd elements in bolder style and print even elements in italic style </p>
<ul>
<li *ngFor="let element of testarray;let odd=odd;let even=even"
[ngClass]="{ odd: odd, even: even }">
{{element.name}} {{element.age}}
</li>
</ul>
.odd{
color:green;
font-weight: bolder;
}
.even{
color:red;
font-style: italic;
}
In this article, you explored how to iterate an array in angular using *ngFor directive.