Loading

*ngFor directive

  • The ngFor directive is a structural directive in Angular that allows you to iterate through a collection, such as an array or a list, and generate dynamic HTML templates based on the elements in that collection. 
  • It's a fundamental building block for creating dynamic and data-driven user interfaces.

Syntax:

*ngFor="let item of collection"

Example:

Step 1: Create an Angular project using Angular CLI.

ng new ng-for-example

Step 2: Create a new component message

ng g c animals

Step 3: Edit the 'animals.component.html' to use '*ngFor' :

<div>
  <h2>List of Animals</h2>
  <ul>
    <li *ngFor="let names of animals">{{names}}</li>
  </ul>
</div>

Step 4: Edit the 'animals.component.ts' to define the component's logic.

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

@Component({
  selector: 'app-animals',
  templateUrl: './animals.component.html',
  styleUrls: ['./animals.component.css']
})
export class AnimalsComponent implements OnInit {

  animals: string[] = ['Cat', 'Dog', 'Lion', 'Horse'];
  constructor() { }

  ngOnInit() {
  }

}

Step 5: Add the ‘<app-animals></app-animals>’ to the ‘app.component.html’ to include the ‘animals component’ in the main application.

<app-animals></app-animals>

Step 6: Now run or compile the application.

ng serve

You will see the result on http://localhost:4200