Angular 8 NgFor Directive Tutorial with Examples

By Digamber Rawat Last updated on
In this Angular 8 tutorial, we are going to understand how useful NgFor directive is. The NgFor is a built-in structural directive, and it is used to loop over a data list and arrays to show the result on front-end.

The *ngFor directive is implemented with HTML template this directive goes through every item in the data collection. NgFor shows the result when we pass the NgFor’s value in the double-curly braces.

Angular 8 NgFor Examples

In the following example we curated a movies list, you’ll see how we are using *ngFor directive to display the movies name using Angular 8 *ngFor directive.

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

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let movie of Movies">
        {{ movie.name }}
      </li>
    </ul>
    `
})

export class AppComponent  {
    Movies: any[] = [
    {
      "name": "Avengers: Endgame"
    },
    {
      "name": "Good Boys"
    },
    {
      "name": "Playmobil: The Movie"
    },
    {
      "name": "Aquarela"
    },
    {
      "name": "Aladdin"
    }, 
    {
      "name": "Downton Abbey"
    }
  ];
}

You will see below output for the above programme:

# Avengers: Endgame
# Good Boys
# Playmobil: The Movie
# Aquarela
# Aladdin
# Downton Abbey

Get Current Items Index using Angular 8 NgFor Directive

In the next step, we will learn to get the current item’s index using Angular 8 *ngFor directive. This can be done very easily using the index variable with ngFor. Have a look in the given below example.

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

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let movie of Movies; let i = index">
        {{ i + 1 }} : {{ movie.name }}
      </li>
    </ul>
   `
})

export class AppComponent  {
    Movies: any[] = [
    {
      "name": "Avengers: Endgame"
    },
    {
      "name": "Good Boys"
    },
    {
      "name": "Playmobil: The Movie"
    },
    {
      "name": "Aquarela"
    },
    {
      "name": "Aladdin"
    }, 
    {
      "name": "Downton Abbey"
    }
  ];
}

Have a look at items index in the following example:

1 : Avengers: Endgame
2 : Good Boys
3 : Playmobil: The Movie
4 : Aquarela
5 : Aladdin
6 : Downton Abbey

As you can see we declared the let i = index with *ngFor directive, we are using the i within the double curly braces. One important thing to remember is the index always starts from 0.

Set First and Last Item Class Name using Angular 8 NgFor Directive

In this example we’ll learn how to target first and last item in a list and set the class name using Angular 8 *ngFor directive.

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

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li 
         *ngFor="let movie of Movies; let first = first; 
         let last = last" [ngClass]="{ first: first, last: last }">
           {{ movie.name }}
      </li>
    </ul>
   `
})


export class AppComponent  {
    Movies: any[] = [
    {
      "name": "Avengers: Endgame"
    },
    {
      "name": "Good Boys"
    },
    {
      "name": "Playmobil: The Movie"
    },
    {
      "name": "Aquarela"
    },
    {
      "name": "Aladdin"
    }, 
    {
      "name": "Downton Abbey"
    }
  ];
}

Above programme will add the CSS class by the name of first and last in HTML list’s 1st and last element.

Nested NgFor

In the next example, we’ll learn how to loop over nested data list using ngFor structured directive.

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

@Component({
  selector: 'my-app',
  template: `
    <ul *ngFor="let collection of industryType">
      <li>{{ collection.type }}</li>
      <ul>
        <li *ngFor="let hollywood of collection.movies">
          {{ hollywood.name }}
        </li>
      </ul>
    </ul>
    `
})

export class AppComponent {
  industryType: any[] = [
    {
      'type': 'Bollywood',
      'movies': [
        {
          "name": "Gully Boy"
        },
        {
          "name": "Manikarnika"
        },
        {
          "name": "Kalank"
        }        
      ]
    },
    {
      'type': 'Hollywood',
      'movies': [
        {
          "name": "Avengers: Endgame"
        },
        {
          "name": "Good Boys"
        },
        {
          "name": "Playmobil"
        },
        {
          "name": "Aquarela"
        }        
      ]
    }
  ];
}

As you can see we have an industryType array which contains Bollywood and Hollywood movies. We used the ngFor directive to loop over the movies group and showed the results.

NgFor Track By

The trackBy method helps in keeping track of collection elements in Angular 8. By default, Angular doesn’t track if any item is being added or removed in the collection. Angular offers trackBy feature it can be used with *ngFor directive. The trackBy feature enhances performance by putting less weight in DOM. In order to use trackBy with NgFor, we should declare a function inside the component class and map it to the ngFor directive as given below:

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

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let movie of Movies; trackBy: trackByFn">
        {{ movie.name }}
      </li>
    </ul>
    `
})

export class AppComponent {

    Movies: any[] = [
    {
      "id": 1,
      "name": "Avengers: Endgame"
    },
    {
      "id": 2,
      "name": "Good Boys"
    },
    {
      "id": 3,
      "name": "Playmobil: The Movie"
    },
    {
      "id": 4,
      "name": "Aquarela"
    },
    {
      "id": 5,
      "name": "Aladdin"
    }, 
    {
      "id": 6,
      "name": "Downton Abbey"
    }
  ];

  // TrackBy
  trackByFn(index:number, movie:any): number {
    return movie.id;
  }
}

Conclusion

Finally, we are done with Angular 8 NgFor Directive tutorial with examples. In this tutorial, we have seen how to iterate over a data collection using ngFor directive. We use ngFor to get the current item Index, set the first and last element CSS class name, loop over nested data collection and learnt to use the trackBy method.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Hire Me