In this article, we will see how to loop through an array using ngFor in Angular.
Looping through array of Strings in angular using ngFor
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <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
1 2 3 4 5 6 7 | export class Fruit { constructor(public id: number, public name: string){ } } |
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 | <div style="text-align:center"> <h1> <p>Fruits : </p> <ul> <li *ngFor="let fruit of fruits"> {{fruit.name}} </li> </ul> </h1> </div> |
© 2019, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post