Home >>Angular8 Tutorial >Angular8 ngFor Directive

Angular8 ngFor Directive

Angular8 ngFor Directive

The * ngFor directive is used to repeat a portion of the HTML template from an iterable list (Collection) once for every object. The ngFor is a structural angular command in AngularJS and is identical to ngRepeat. Some local variables, such as Index, First, Last, odd and even * ngFor directive are exported.

Syntax of ngFor

See the simplified syntax for the ngFor directive:

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

How to use ngFor Directive?

You need to build a block of HTML elements to Use ngFor directive, which can show a single item in the list of objects. You may use the ngFor directive after that to tell angular to repeat the block of HTML elements for each item in the list.

Example for *ngFor Directive

First, you must build an Application with angular. Open the app.component.ts after that, and add the code below.

The following code contains a list of Top 3 movies in a movie. Let's build a template that shows these movies in a tabular form.

import { Component } from '@angular/core';  
    selector: 'movie-app',  
export class AppComponent   
    title: string ="Top 10 Movies" ;  
    movies: Movie[] =[  
        {title:'Zootopia',director:'Byron Howard, Rich Moore',cast:'Idris Elba, Ginnifer Goodwin, Jason Bateman',releaseDate:'March 4, 2016'},  
        {title:'Batman v Superman: Dawn of Justice',director:'Zack Snyder',cast:'Ben Affleck, Henry Cavill, Amy Adams',releaseDate:'March 25, 2016'},  
        {title:'Captain America: Civil War',director:'Anthony Russo, Joe Russo',cast:'Scarlett Johansson, Elizabeth Olsen, Chris Evans',releaseDate:'May 6, 2016'},  
        {title:'X-Men: Apocalypse',director:'Bryan Singer',cast:'Jennifer Lawrence, Olivia Munn, Oscar Isaac',releaseDate:'May 27, 2016'},  
class Movie {  
    title : string;  
    director : string;  
    cast : string;  
    releaseDate : string;  

Now, open the app. component.html and add the following code:

<div class='panel panel-primary'>  
    <div class='panel-heading'>  
    <div class='panel-body'>  
        <div class='table-responsive'>  
            <table class='table'>  
                        <th>Release Date</th>  
                    <tr *ngFor="let movie of movies;">  

It will display the movies in tabular form when you run the application.