Angular ngFor

Last Updated on May 22, 2022
Angular ngFor

Angular ngFor

In Angular ngFor structural directive allows us to iterate over the collection of an array, list, etc. ngFor directive helps us to create the HTML elements like table rows or some kinds of list of data values from the array. The ngFor works are like the For-Loop statement in other programming languages.

Let’s look at code syntax and some code examples of using ngFor.


<some-element ngFor="let <item> of <items>;”> 
    <html-Template></html-Template>
</some-element>

Let's take a look at an example of how to iterate the array values using Angular ngFor.


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

@Component({
    selector: 'app-demoComponent',
    template:  `
            <ul *ngFor="let lang of listOfProgrammingLang;">
                <li>{{lang}}</li>
            </ul>
        `
    })

export class DemoComponent {

    //List of some programming languages as an array
    listOfProgrammingLang = ["JavaScript", "Python", "Csharp", "AspDotNet", "HTML"];

    constructor(){ 
        //Constructor
    }
}

As an output, we will see the list of array values.

JavaScript
Python
Csharp
AspDotNet
HTML

Let's see another example of how to iterate the JSON data using ngFor.


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

@Component({
    selector: 'app-demoComponent',
    template:  `
            <table class="table">
                <thead>
                    <tr>
                        <th class="col">#</th>
                        <th class="col">Brand</th>
                        <th class="col">Country</th>
                        <th class="col">Product Type</th>
                    </tr>
                </thead>
            <tbody *ngFor="let computer of listOfComputers; index as i">
                <tr>
                    <td>{{i+1}}</td> //So it can start from 1 rather than 0
                    <td>{{computer.Brand}}</td>
                    <td>{{computer.Country}}</td>
                    <td>{{computer.Product_Type}}</td>
                </tr>
            </tbody>
        </table>
        `
    })

export class DemoComponent {

    //List of some computer info in Json 
    listOfComputers = [
        {Brand: "Lenovo", Country:"China", Product_Type:"Yoga"},
        {Brand: "HP", Country:"United States", Product_Type:"Elitebook"},
        {Brand: "Dell", Country:"United States", Product_Type:"Vostro"},
        {Brand: "Apple", Country:"United States", Product_Type:"MacBook"},
        {Brand: "Asus", Country:"Taiwan", Product_Type:"ZenBook"},
        {Brand: "Lenovo", Country:"China", Product_Type:"Legion"}
    ];

    constructor(){ 
        //Constructor
    }
}

As an output, we will see the list of all computer information in HTML table format.