In Angular, the “ngFor” directive is used to loop through arrays and display the data.
In this article, we will see how to loop through an array using ngFor in Angular and display its data.
Basic Usage of ngFor
The basic syntax of “ngFor” is as follows:
<ul> <li *ngFor="let item of items">{{ item }}</li> </ul>
Here, ngFor is used to loop through the items array and display each item in a list.
The “let item of items” syntax is used to specify the variable name (item) and the array (items) to loop through.
Accessing the Index of the Current Item
In addition to the item itself, you can also access the index of the current item using the index keyword.
<ul> <li *ngFor="let item of items; index as i">{{ i }} - {{ item }}</li> </ul>
In this example, the “index as i” syntax is used to specify the name of the index variable (i).
Looping through array of Strings in angular using ngFor
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { message = 'Hello World'; fruits = ['Apple', 'Banana', 'Orange', 'Pineapple']; }
app.component.html
<div style="text-align:center"> <h1> {{message}} <p>Fruits : </p> <ul> <li *ngFor="let fruit of fruits"> {{fruit}} </li> </ul> </h1> </div>
Looping through an array of custom Objects using ngFor in Angular
Here, we will create a data class for fruits and loop over them using *ngFor.
We can create a data class for Fruits using :
ng generate class fruit
fruit.ts
export class Fruit { constructor(public id: number, public name: string){ } }
app.component.ts
import { Component } from '@angular/core'; import { Fruit } from './fruit'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { message = 'Hello World'; fruits = [new Fruit(1,'Apple'), new Fruit(2, 'Banana'), new Fruit(3, 'Orange'), new Fruit(4, 'Pineapple')]; }
app.component.html
<div style="text-align:center"> <h1> <p>Fruits : </p> <ul> <li *ngFor="let fruit of fruits"> {{fruit.name}} </li> </ul> </h1> </div>
© 2019 – 2023, https:. All rights reserved. On republishing this post, you must provide link to original post