AppDividend
Latest Code Tutorials

Angular NgFor Tutorial With Example | NgForOf Directive

0 201

Get real time updates directly on you device, subscribe now.

Angular NgFor Tutorial With Example | NgForOf Directive is today’s topic. NgFor structural directive renders the template for each item in the collection. 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.

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

 

Angular NgFor Tutorial With Example | NgForOf Directive

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.

 

Use a ngFor directive to render HTML items

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.

Related Posts
1 of 22
<!-- 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.

 

How to stripe a table using even and odd

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.

 

Identifying the first and the last row of a table

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

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.