Angular 9/8 ngFor Directive: Render Arrays with ngFor by Example

Angular 9/8 ngFor Directive: Render Arrays with ngFor by Example

In this quick how-to tutorial we'll be learning about the ngFor directive in Angular and how to use it to display arrays of data in your Angular templates.

We'll be using Angular 9 for the example.

We'll learn about these things:

  • What ngFor does in Angular and how it's used?
  • What is the variable visibility/scope inside an ngFor loop?
  • How to find the index position of an element inside an ngFor loop?
  • Getting the first and the last element inside an ngFor loop

Let's get started with our tutorial to master ngFor in Angular!

Check out How to repeat an HTML element or component multiple times in Angular 9/8?

What ngFor does in Angular and how it's used?

ngFor is a core Angular directive that can be used as a part if Angular template syntax to entend HTML with an easy way to itertave over lists of data right inside the component's template.

You can use `ngFor lists and tables in HTML templates. For example, let's consider the following array of objects representing a set of products in a component:


const PRODUCTS = [
    {"id":1,"name":"Licensed Frozen Hat","description":"Incidunt et magni","price":"170.00","quantity":56840},
    {"id":2,"name":"Rustic Concrete Chicken","description":"Sint libero mollitia","price":"302.00","quantity":9358},
    {"id":3,"name":"Fantastic Metal Computer","description":"In consequuntur cupiditat","price":"279.00","quantity":90316},
    {"id":4,"name":"Refined Concrete Chair","description":"Saepe nemo praesentium","price":"760.00","quantity":5899}
];

Using ngFor, we can iterate over the PRODUCTS array in the associated template and render/display data using an HTML list or table:

<ul>
<li *ngFor="let product of products">
    <h2>{{product.name}} / ${{product.price}}</h2>
    <p> {{product.description}} </p>
</li>
</ul>

Let's now understand more about ngFor.

What is the syntax of ngFor?

Let's see how ngFor works by building a practical example. We'll only see how to create a component with an associated HTML template so you should already have an Angular development environment ready with Angular CLI v9 installed and a project generated. Both these two things can be done with the following two commands:

$ npm install @angular/cli
$ ng new angular-ngfor-example

Go ahead and navigate inside inside your project's folder and generate a component with the following commands:

$ cd ./angular-ngfor-example
$ ng generate component products 

Open the src/app/products/products.component.ts file and add the products array as a member of ProductsComponent as follows:

import { Component, OnInit } from '@angular/core';  

@Component({  
    selector: 'app-products',  
    templateUrl: './products.component.html',  
    styleUrls: ['./products.component.css']  
})  
export class ProductsComponent implements OnInit {
    products = [
    {"id":1,"name":"Licensed Frozen Hat","description":"Incidunt et magni","price":"170.00","quantity":56840},
    {"id":2,"name":"Rustic Concrete Chicken","description":"Sint libero mollitia","price":"302.00","quantity":9358},
    {"id":3,"name":"Fantastic Metal Computer","description":"In consequuntur cupiditat","price":"279.00","quantity":90316},
    {"id":4,"name":"Refined Concrete Chair","description":"Saepe nemo praesentium","price":"760.00","quantity":5899}
];;
    constructor() { }
    ngOnInit() {
    }
}

Next, open the src/app/products/products.component.html file and update it as follows:

<ul>
<li *ngFor="let product of products">
    <h2>{{product.name}} / ${{product.price}}</h2>
    <p> {{product.description}} </p>
</li>
</ul>

When rendered, a <ul> element will be created with an item for each product in the array. Let's understand the basic syntax if ngFor:

  • ngFor gets an expression comprised of let and of keywords and variables;
  • of is followed by the array that we are iterating over. In our example, it's products which is defined in the associated component class;
  • let is used to define a variable that will contain the data for each iteration. In our example, we named it product but you can name what's you think is convenient.

What's the Scope of the ngFor Loop Variable?

The variable used to represent the data availabe for each iteration inside an ngFor directive is only only visible inside the loop.

How to Get the Index of an Element Inside an ngFor Loop?

You can get the index of the current element in the ngFor loop by using the index variable:

<ul>
<li *ngFor="let product of products; let num = index">
    <h2># {{num}} {{product.name}} / ${{product.price}}</h2>
    <p> {{product.description}} </p>
</li>
</ul>

Conclusion

In this quick tutorial, we have learned about the ngFor directive in Angular 9/8. Check out this tutorial for a complete Angular 8 example that demonstrates how we can use ngFor to display an array of fetched data in our HTML template.



Angular 9 Components: Input and Output
Angular 13 selectors
Picture-in-Picture with JavaScript and Angular 10
Jasmine Unit Testing for Angular 12
Angular 9 Tutorial By Example: REST CRUD APIs & HTTP GET Requests with HttpClient
Angular 10/9 Elements Tutorial by Example: Building Web Components
Angular 10/9 Router Tutorial: Learn Routing & Navigation by Example
Angular 10/9 Router CanActivate Guards and UrlTree Parsed Routes
Angular 10/9 JWT Authentication Tutorial with Example
Style Angular 10/9 Components with CSS and ngStyle/ngClass Directives
Upload Images In TypeScript/Node & Angular 9/Ionic 5: Working with Imports, Decorators, Async/Await and FormData
Angular 9/Ionic 5 Chat App: Unsubscribe from RxJS Subjects, OnDestroy/OnInit and ChangeDetectorRef
Adding UI Guards, Auto-Scrolling, Auth State, Typing Indicators and File Attachments with FileReader to your Angular 9/Ionic 5 Chat App
Private Chat Rooms in Angular 9/Ionic 5: Working with TypeScript Strings, Arrays, Promises, and RxJS Behavior/Replay Subjects
Building a Chat App with TypeScript/Node.js, Ionic 5/Angular 9 & PubNub/Chatkit
Chat Read Cursors with Angular 9/Ionic 5 Chat App: Working with TypeScript Variables/Methods & Textarea Keydown/Focusin Events
Add JWT REST API Authentication to Your Node.js/TypeScript Backend with TypeORM and SQLite3 Database
Building Chat App Frontend UI with JWT Auth Using Ionic 5/Angular 9
Install Angular 10 CLI with NPM and Create a New Example App with Routing
Styling An Angular 10 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and Cards
Integrate Bootstrap 4/jQuery with Angular 10 and Styling the UI With Navbar and Table CSS Classes
Angular 10/9 Tutorial and Example: Build your First Angular App
Angular 9/8 ngIf Tutorial & Example
Angular 10 New Features
Create New Angular 9 Workspace and Application: Using Build and Serve
Angular 10 Release Date: Angular 10 Will Focus on Ivy Artifacts and Libraries Support
HTML5 Download Attribute with TypeScript and Angular 9
Angular 9.1+ Local Direction Query API: getLocaleDirection Example
Angular 9.1 displayBlock CLI Component Generator Option by Example
Angular 9 Basics Tutorial by Example
Angular 9/8 ngFor Directive: Render Arrays with ngFor by Example
Responsive Image Breakpoints Example with CDK's BreakpointObserver in Angular 9/8
Angular 9/8 DOM Queries: ViewChild and ViewChildren Example
The Angular 9/8 Router: Route Parameters with Snapshot and ParamMap by Example
Angular 9/8 Nested Routing and Child Routes by Example
Angular 9 Examples: 2 Ways To Display A Component (Selector & Router)
Angular 9/8 Tutorial: Http POST to Node/Express.js Example
Angular 9/8 Feature and Root Modules by Example
Angular 9/8 with PHP: Consuming a RESTful CRUD API with HttpClient and Forms
Angular 9/8 with PHP and MySQL Database: REST CRUD Example & Tutorial
Unit Testing Angular 9/8 Apps Tutorial with Jasmine & Karma by Example
Angular 9 Web Components: Custom Elements & Shadow DOM
Angular 9 Renderer2 with Directives Tutorial by Example
Build Progressive Web Apps (PWA) with Angular 9/8 Tutorial and Example
Angular 9 Internationalization/Localization with ngx-translate Tutorial and Example
Create Angular 9 Calendar with ngx-bootstrap datepicker Example and Tutorial
Multiple File Upload with Angular 9 FormData and PHP by Example
Angular 9/8 Reactive Forms with Validation Tutorial by Example
Angular 9/8 Template Forms Tutorial: Example Authentication Form (ngModel/ngForm/ngSubmit)
Angular 9/8 JAMStack By Example
Angular HttpClient v9/8 — Building a Service for Sending API Calls and Fetching Data
Build an Angular 9/8 CRUD Example & Tutorial
Styling An Angular 9/8/7 Example App with Bootstrap 4 Navbar, Jumbotron, Tables, Forms and Cards
Angular 8/7 Tutorial By Example: (REST API, HttpClient GET, Components, Services & ngFor)

✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

✋ Want to master Angular 14? Read our angular tutorial and join our #DailyAngularChallenge where we learn to build components, directives, services, pipes and complete web, mobile, and desktop applications with latest Angular version.

✋ Make sure to join our Angular 14 Dev Community 👈 to discuss anything related to Angular development.

❤️ Like our page and subscribe to our feed for updates!