Loading
*ngFor directive
In Angular, the *ngFor directive makes it easy to display lists of items dynamically. Think of it as telling Angular
Go through each item in this list, and create an HTML element for it.
It is a structural directive, which means it changes the structure of the DOM by creating or removing elements based on your data.



Syntax:

<element *ngFor="let item of collection">
  {{item}}
</element>

  • collection - is usually an array (like a list of names, animals, products, etc.)
  • item - represents each element in that array as Angular loops over it



Example: Using ngFor in Angular


Step 1: Create a New Angular Project

ng new ng-for-example



Step 2: Generate a New Component

ng g c animals



Step 3: Use ngFor in the Template

Edit animals.component.html

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

Here,

  • We loop through the animals array
  • For each animal, Angular creates an <li> element showing its name



Step 4: Add the Data in the Component

Edit animals.component.ts

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() {}
}

This creates an array named animals with four animal names.



Step 5: Show the Component in Your App

In app.component.html, add

<app-animals></app-animals>

This tells Angular to render your new AnimalsComponent inside the main app.



Step 6: Run the App

ng serve


Open your browser and go to: http://localhost:4200


You will see a list

  • Cat
  • Dog
  • Lion
  • Horse