Angular 8 *ngFor Directive

To repeat a section of an HTML template once per each item from an iterable list or a Collection, the *ngFor directive is used. Along with being an Angular structural directive, the *ngFor directive is also similar to NngRepeat in AngularJS. The *ngFor directive exports some local variables like Index, First, Last, odd and even.

Syntax: Simplified syntax:

<li *ngFor="let item of items;"> .... </li>

To use ngFor Directive:

Create a block of HTML elements to display a single item of the items collection in order to use ngFor directive. The ngFor directive thus instructs angular to repeat the respective block of HTML elements for each item in the list.

Example:

Step 1: Create an Angular Application.

Step 2: Open the app.component.ts to add the below code.

app.component.ts:

import { Component } from '@angular/core';  
@Component({  
    selector: 'bday-app',  
    templateUrl:'./app/app.component.html',  
    styleUrls:['./app/app.component.css']  
})  
export class AppComponent   
{   
    title: string ="Birth Date of respective member in the family" ;  
    bdays: BDay[] =[  
        {name:'James Cruise',bDate:'July 14, 1970'},  
        {name:'Maria Cruise',bDate:'April 18, 1975'},  
        {name:'Katherine Cruise',bDate:'March 25, 1991'},  
    ]  
}   
class BDay {  
    name : string;  
    bDate : string;  
}

Explanation:

The above code includes a list of members in a family in a BDay array.

Step 3: Open the app. component.html to add the below code:

app.component.html:

<div class='panel panel-primary'>  
    <div class='panel-heading'>  
        {{title}}  
    </div>   
    <div class='panel-body'>  
        <div class='table-responsive'>  
            <table class='table'>  
                <thead>  
                    <tr>  
                        <th>Name</th>   
                        <th>Birth Date</th>  
                    </tr>  
                </thead>  
                <tbody>  
                    <tr *ngFor="let bday of bdays;">  
                        <td>{{bday.name}}</td>  
                        <td>{{bday.bDate}}</td>  
                    </tr>  
                </tbody>  
            </table>  
        </div>  
    </div>  
</div>

Explanation:

In the above code, we are creating a template that will display the list of birth dates in a tabular form, on running the application.

Please follow and like us:
Content Protection by DMCA.com