Tuesday, June 29, 2021

Angular ngFor Directive With Examples

Angular ngFor directive is the looping directive in Angular that iterates over each item in the collection and renders the element (or section of elements) for each item.

Here is an example where ngFor is contained in an <li> element.

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

Note that ngFor is the shorthand form which is internally expanded into a long form that uses the ngForOf selector on an <ng-template> element.

<ng-template ngFor let-item [ngForOf]="items">
  <li>...</li>
</ng-template>

Note that asterisk (*) precedes the ngFor which means it is a structural directive and used to add or remove DOM element.

Angular ngFor example

Following example shows how to iterate through an Array of User instances using ngFor and display the fields in a table.

User Model class

user.model.ts class with fields.

export class User {
  name : string;
  age : number;
  joinDate : Date;
  constructor(name: string, age : number, joinDate : Date) {
    this.name = name;
    this.age = age;
    this.joinDate  = joinDate;
  }
}

Component class

import { Component } from '@angular/core';
import { User } from './user/user.model';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  users: User[];

  constructor(){
    // Adding User instances to users array
    this.users = [new User('Jack', 56, new Date('2005-03-25')),
    new User('Lisa', 32, new Date('2012-05-09')),
    new User('Jayesh', 28, new Date('2014-10-21'))] ;
  }
}

You can also use JSON format to add instances to array.

this.users = [
  { name: 'Anderson', age: 35, joinDate: new Date('2005-03-25') },
  { name: 'John', age: 12, joinDate: new Date('2012-05-09') },
  { name: 'Peter', age: 22, joinDate: new Date('2014-10-21') }
];

Template ( app.component.html)

<div class="container">
  <h2>User Details</h2>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Joining Date</th>
    </tr>
    <tr *ngFor="let user of users">
      <td>{{user.name}}</td>
      <td>{{user.age}}</td>
      <td>{{user.joinDate | date:'dd/MM/yyyy'}}</td>
    </tr>
  </table>
</div>

In the template ngFor directive is used to iterate through the array of users, ngFor is contained in a <tr> element so each iteration creates a new row in the table.

<tr *ngFor="let user of users">
Angular ngFor directive

ngFor directive values

ngFor directive provides exported values that can be assigned to local variables and then used with in the element.

  • index: number- The index of the current item in the iterable.
  • count: number- The length of the iterable.
  • first: boolean- True when the item is the first item in the iterable.
  • last: boolean- True when the item is the last item in the iterable.
  • even: boolean- True when the item has an even index in the iterable.
  • odd: boolean- True when the item has an odd index in the iterable.

NgFor index value example

if you want to provide serial number too as a column in the table that can be done using the index value.

<div class="container">
  <h2>User Details</h2>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>S. No</th>
      <th>Name</th>
      <th>Age</th>
      <th>Joining Date</th>
    </tr>
    <tr *ngFor="let user of users; index as i;">
      <td>{{i+1}}</td>
      <td>{{user.name}}</td>
      <td>{{user.age}}</td>
      <td>{{user.joinDate | date:'dd/MM/yyyy'}}</td>
    </tr>
  </table>
</div>
ngFor with index

NgFor index odd-even example

Using odd and even values you can style the alternate rows.

<div class="container">
  <h2>User Details</h2>
  <table class="table table-sm table-bordered m-t-4">
    <tr>
      <th>S. No</th>
      <th>Name</th>
      <th>Age</th>
      <th>Joining Date</th>
    </tr>
    <tr *ngFor="let user of users; let i = index; let odd = odd;"
      [class.bg-info]="!odd">
      <td>{{i+1}}</td>
      <td>{{user.name}}</td>
      <td>{{user.age}}</td>
      <td>{{user.joinDate | date:'dd/MM/yyyy'}}</td>
    </tr>
  </table>
</div>
Angular ngFor odd even

Same way you can also use first and last values if you want to do something specific for the first and/or the last row while iterating.

That's all for this topic Angular ngFor Directive With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Angular Tutorial Page


Related Topics

  1. Angular ngSwitch Directive With Examples
  2. Angular ngIf Directive With Examples
  3. Angular ngStyle Directive With Examples
  4. Directives in Angular
  5. How to Add Bootstrap to Angular Application

You may also like-

  1. Angular First App - Hello world Example
  2. Angular Class Binding With Examples
  3. Angular Two-Way Data Binding With Examples
  4. CanDeactivate Guard in Angular With Example
  5. Unmodifiable or Immutable List in Java
  6. Initializer Block in Java
  7. java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java
  8. Python Program to Display Armstrong Numbers

No comments:

Post a Comment