Angular 2 ngFor Directive

Angular 2 ngFor Directive

In this article, I am going to discuss the Angular 2 ngFor Directive with an example. The Directives are one of the most important features of Angular applications. They are used to extend the power of HTML attributes.

There are three kinds of directives in an Angular application. They are as follows

Components

The Angular Component also refers to a directive with a template which deals with the View of the Application and also contains the business logic. It is also very important to divide your Application into smaller parts. In other words, we can say that Components are directives that are always associated with the template directly. We already discussed this in our previous articles.

Structural Directives

The Structural directives are the directives which are used to change the behavior of DOM by adding and removing DOM elements. The directive NgFor, NgSwitch, and NgIf are some of the examples of structural directives. If already discussed the NgIf directive in our previous article, In this article, we are going to discuss the NgFor directive.

Attribute Directives

The Attribute directives are also used to change the behaviour of DOM. The directive NgStyle is an example of Attribute directives which is used to change styles of the DOM elements.

What is Angular 2 ngFor Directive?

The ngFor is a built-in structural directive in Angular which is very much similar to the for loop used in most of the programming languages. So, the NgFor directive is used to iterate over a collection of data. It is used to customize the data display.

Let us understand the ngFor structural directive with an example. We are going to use the following array of Student objects in this demo.

Angular 2 ngFor Directive

Then we want to display the above students in a table on a web page as shown below. 

We are going to work with the same project that we have been working so far of this article series.

Let’s discuss the Step By Step Procedure to achieve this:

Step1: 

Add a new TypeScript file within the “Student” folder with the name StudentList.Component.ts and then Copy and paste the below code in it. 

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

@Component({
    selector: 'student-list',
    templateUrl: 'app/Student/StudentList.Component.html',
    styleUrls: ['app/Student/StudentList.Component.css']
})

export class StudentListComponent {    
    students: any[] = [
        {
            ID: 'std101', FirstName: 'Pranaya', LastName: 'Rout', Branch: 'CSE',
            DOB: '29/02/1988', Gender: 'Male', Mobile: 9876543210
        },
        {
            ID: 'std102', FirstName: 'Anurag', LastName: 'Mohanty', Branch: 'ETC',
            DOB: '23/05/1989', Gender: 'Male', Mobile: 1112223334
        },
        {
            ID: 'std103', FirstName: 'Priyanka', LastName: 'Dewangan', Branch: 'CSE',
            DOB: '24/07/1992', Gender: 'Female', Mobile: 1234567890
        },
        {
            ID: 'std104', FirstName: 'Hina', LastName: 'Sharma', Branch: 'ETC',
            DOB: '19/08/1990', Gender: 'Female', Mobile: 3334445550
        },
        {
            ID: 'std105', FirstName: 'Sambit', LastName: 'Satapathy', Branch: 'CSE',
            DOB: '12/94/1991', Gender: 'Male', Mobile: 9998887770
        }
    ];
}
Step2:

Add a new StyleSheet file within the “Student” folder and name it as StudentList.Component.css and then copy and paste the following code in it.

table {
    color: #369;
    font-family: Arial, Helvetica, sans-serif;
    font-size: large;
    border-collapse: collapse;
}

td {
    border: 1px solid #369;
    padding:5px;
}

th{
    border: 1px solid #369;
    padding:5px;
}
Step3:

Add a new HTML page within the “Student” folder and name it as StudentList.Component.html and then copy and paste the following code in it.

<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Branch</th>
            <th>DOB</th>
            <th>Gender</th>
            <th>Mobile</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor='let student of students'>
            <td>{{student.ID}}</td>
            <td>{{student.FirstName}}</td>
            <td>{{student.LastName}}</td>
            <td>{{student.Branch}}</td>
            <td>{{student.DOB}}</td>
            <td>{{student.Gender}}</td>
            <td>{{student.Mobile}}</td>
        </tr>
        <tr *ngIf="!students || students.length==0">
            <td colspan="7">
                No Students to display
            </td>
        </tr>
    </tbody>
</table>
Points to Remember:
  1. The ngFor directive is usually used to iterate over a collection. In our case, the collection is an array of students.
  2. As the ngFor is a structural directive, so it is prefixed with * (star).
  3. *ngFor=’let student of students – In this statement, the ‘student’ is called template input variable, which can be accessed by the <tr> element and any of its child elements.
  4. The ngIf structural directive displays the row No Students to display when the students property does not exist or when there is no students in the array.
Step4: 

In the root module, i.e. in the app.module.ts which is present inside the app folder, import the StudentList component and then add it to the declarations array as shown below. 

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { StudentListComponent } from './Student/StudentList.component';

@NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent, StudentListComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }
Step5: 

In the root component, i.e. app.component.ts use the StudentList component as a directive as shown below. 

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

@Component({
    selector: 'my-app',
    template: '<student-list></student-list>'
})

export class AppComponent {}

That’s it. We have done with our implementation. Now run the application and you will notice that the students are displayed in the table as expected. 

In the next article, I will discuss the Angular ngFor trackBy with an example.

SUMMARY:

In this article, I try to explain the Angular 2 ngFor directive with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *