ngFor Directive in Angular Tutorial

beginner
7 min

ngFor Directive in Angular Tutorial

Welcome to the ngFor Directive lesson at CodeYourCraft! Today, we're going to dive into one of the most powerful and widely-used Angular directives - the ngFor Directive. This tutorial is designed to be beginner-friendly, yet comprehensive enough for intermediate learners. Let's get started!

Understanding ngFor Directive 💡

The ngFor Directive is used to iterate over arrays, maps, or any iterable objects in Angular. It's a convenient way to display lists or repetitive data in our templates.

Syntax 📝

html
<ng-container *ngFor="let item of items; index as i"> <!-- Content to be repeated for each item --> </ng-container>
  • let item: A local variable to access each item in the iterable object.
  • of items: The iterable object (array, map, etc.).
  • index as i: An optional parameter to get the index of the current item (zero-based).

Practical Example 🎯

Let's create a simple example where we'll display a list of fruits.

typescript
import { Component } from '@angular/core'; @Component({ selector: 'app-fruit-list', template: ` <ul> <li *ngFor="let fruit of fruits"> {{ fruit }} </li> </ul> `, }) export class FruitListComponent { fruits = ['Apple', 'Banana', 'Orange']; }

In this example, we have a FruitListComponent with an array of fruits. The ngFor directive is used to iterate over this array and create an <li> element for each fruit.

Advanced Example 💡

Sometimes, we need to manipulate the data while iterating. Here's an example where we'll add a "Remove" button next to each fruit, allowing us to remove fruits from the list.

typescript
import { Component, EventEmitter, Output } from '@angular/core'; @Component({ selector: 'app-fruit-list', template: ` <ul> <li *ngFor="let fruit of fruits; index as i; let even = odd; let odd = even"> <button (click)="removeFruit(i)">Remove</button> {{ fruit }} <ng-container *ngIf="even">, </ng-container> </li> </ul> `, }) export class FruitListComponent { fruits = ['Apple', 'Banana', 'Orange']; @Output() fruitRemoved = new EventEmitter<string>(); removeFruit(index: number) { this.fruits.splice(index, 1); this.fruitRemoved.emit(this.fruits[index]); } }

In this example, we've added a Remove button for each fruit and used the index to remove fruits from the list. When a fruit is removed, we also emit an event fruitRemoved with the removed fruit.

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the `*ngFor` directive do in Angular?

That's it for today! We've covered the basics and an advanced example of using the ngFor Directive in Angular. In the next lesson, we'll dive deeper into Angular templates and components. Happy learning! 📝 🎉