Angular NgFor Tutorial With Example | NgForOf Directive

Angular NgFor Tutorial With Example | NgForOf Directive

Angular NgFor Tutorial With Example | NgForOf Directive is today’s topic. NgFor structural directive renders the template for each item in the collection.

Originally published by Krunal at appdividend.com

The ngForOf is generally used in the shorthand form *ngFor. The core directive ngFor allows us to build data presentation lists and tables in our HTML templates. When we need to display data in Angular, we use the ngFor directive.

Content Overview 

  • 1 Angular NgFor Tutorial With Example
  • 2 Step 1: Install Angular
  • 3 Step 2: Create a Model file.
  • 4 Step 3: Use a ngFor directive to render HTML table
  • 5 Step 4: How to stripe a table using even and odd
  • 6 Step 5: Identifying the first and the last row of a table

Angular NgFor Tutorial With Example

Let’s see the Syntax of the NgFor directive.

<ng-template *ngFor="let item of items; index as i; trackBy: trackByFn">...</ng-template>

Let’s take an example of the ngFor directive in Angular.

Step 1: Install Angular

If you do not have the latest Angular CLI, then you need to update your CLI. For more guidance, see this tutorial. Now, create a new project using the following command.

ng new angfor

 

Now, go inside the folder and open the folder in Visual Studio Code.

Next, install the Bootstrap 4 CSS Framework using the following command.

npm install bootstrap --save

Now, add the bootstrap css file inside the angular.json file.

"styles": [
    "src/styles.css",
    "./node_modules/bootstrap/dist/css/bootstrap.min.css"
],

Step 2: Create a Model file.

Inside the src >> app folder, create one file called Character.ts file and add the following code inside it.

// Character.ts

export default class Character { actor_name: String; character_name: String; gender: String; status: String; }

We will display the Game of Thrones characters and their properties like actor_name,character_namegenderstatus, etc.

Now, create an array of data inside the app.component.ts file.

// app.component.ts

import { Component } from '@angular/core'; import Character from './Character'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { characters: Character[] = [ { actor_name: 'Peter Dinklage', character_name: 'Tyrion Lannister', gender: 'Male', status: 'Alive' }, { actor_name: 'Sean Bean', character_name: 'Ned Stark', gender: 'Male', status: 'Dead' }, { actor_name: 'Emilia Clark', character_name: 'Khaleesi', gender: 'Female', status: 'Alive' }, { actor_name: 'Catelyn Stark', character_name: 'Michelle Fairley', gender: 'Female', status: 'Dead' } ]; }

So, now we have data that can be rendered inside an HTML view using the ngFor directive.

Step 3: Use a ngFor directive to render HTML table

Let’s create the component so that we can have a working HTML. Write the following code inside an app.component.html file.

<!-- app.component.html -->

<div class="container"> <table class="table table-striped"> <thead> <tr> <th>Actor Name</th> <th>Character Name</th> <th>Gender</th> <th>Status</th> </tr> </thead> <tbody> <tr *ngFor="let character of characters"> <td>{{ character.actor_name }}</td> <td>{{ character.character_name }}</td> <td>{{ character.gender }}</td> <td>{{ character.status }}</td> </tr> </tbody> </table> </div>

Save the file and go to the terminal and start the angular dev server.

ng serve --open

See the output in the browser.

 

So, the ngFor directive has generated the HTML rows.

This template will generate the HTML table that we showed just above. We can see in this example the (most common) syntax for using ngFor is following.

  • We are passing to ngFor an iteration expression
  • The loop variable named character is defined using the keyword let, which is consistent with Javascript syntax.

Let’s add an index in the table. Write the following code inside an app.component.html file.

<!-- app.component.html -->

<div class="container"> <table class="table table-striped"> <thead> <tr> <th>Index</th> <th>Actor Name</th> <th>Character Name</th> <th>Gender</th> <th>Status</th> </tr> </thead> <tbody> <tr *ngFor="let character of characters; let i = index"> <td>{{ i+1 }}</td> <td>{{ character.actor_name }}</td> <td>{{ character.character_name }}</td> <td>{{ character.gender }}</td> <td>{{ character.status }}</td> </tr> </tbody> </table> </div>

So, we can add the i as a local variable and display inside the columns using the below code.

<tr *ngFor="let character of characters; let i = index">
        <td>{{ i+1 }}</td>

In the output, we can see the Index, which starts from 1.

Step 4: How to stripe a table using even and odd

NgForOf provides exported values that can be aliased to local variables.

The following exported values can be aliased to local variables.

  1. $implicit: T: The value of all the individual items in the iterable (ngForOf).
  2. ngForOfNgIterable<T>: The value of an iterable expression. Useful when the expression is more complicated then property access, for example when using the async pipe (userStreams | async).
  3. index: number: An index of the current item in the iterable.
  4. first: boolean: True when an item is the first item in the iterable.
  5. last: boolean: True when an item is the last item in the iterable.
  6. even: boolean: True when an item has an even index in the iterable.
  7. odd: boolean: True when an item has an odd index in the iterable.

Now, we use even and odd local variables to differentiate the rows of the table.

We use the NgClass conditional directive. Write the following code inside the app.component.css file. We will define two classes 1) even 2) odd. Then we use those classes based on the even and odd local variable inside the ngFor directive.

.odd {
  background-color: beige;
}
.even {
  background-color: aquamarine;
}

Now, write the following code inside the app.component.html file.

<!-- app.component.html -->

<div class="container"> <table class="table table-responsive"> <thead> <tr> <th>Index</th> <th>Actor Name</th> <th>Character Name</th> <th>Gender</th> <th>Status</th> </tr> </thead> <tbody> <tr *ngFor="let character of characters; let i = index; let even = even; let odd = odd" [ngClass]="{ odd: odd, even: even }"> <td>{{ i }}</td> <td>{{ character.actor_name }}</td> <td>{{ character.character_name }}</td> <td>{{ character.gender }}</td> <td>{{ character.status }}</td> </tr> </tbody> </table> </div>

In the above code, see the ngFor directive, we have used the local variables like odd and even. Then we have used the ngClass directive to assign the different classes based on the odd and even values.

Save the file and see the output.

 

Step 5: Identifying the first and the last row of a table

We have seen the odd and even. Now, see the first and last element.

First, define the two classes inside the app.component.css file.

.first {
  background-color: blanchedalmond;
}
.last {
  background-color: cadetblue;
}

Now, write the following code inside the app.component.html file.

<!-- app.component.html -->

<div class="container"> <table class="table table-responsive"> <thead> <tr> <th>Index</th> <th>Actor Name</th> <th>Character Name</th> <th>Gender</th> <th>Status</th> </tr> </thead> <tbody> <tr *ngFor="let character of characters; let i = index; let first = first; let last = last" [ngClass]="{ first: first, last: last }"> <td>{{ i }}</td> <td>{{ character.actor_name }}</td> <td>{{ character.character_name }}</td> <td>{{ character.gender }}</td> <td>{{ character.status }}</td> </tr> </tbody> </table> </div>

So, now it will change the background color of the first and last row. See the output below.

 

Finally, the Angular NgFor Tutorial With Example | NgForOf Directive is over.

Originally published by Krunal at appdividend.com

==========================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Angular 8 (formerly Angular 2) - The Complete Guide

☞ Complete Angular 8 from Zero to Hero | Get Hired

☞ Learn and Understand AngularJS

☞ The Complete Angular Course: Beginner to Advanced

☞ Angular Crash Course for Busy Developers

☞ Angular Essentials (Angular 2+ with TypeScript)

☞ Angular (Full App) with Angular Material, Angularfire & NgRx

☞ Angular & NodeJS - The MEAN Stack Guide




angular web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill. Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.