Angular Lists

Angular Lists (*ngFor)

Rendering lists of identical items (like products, users, or messages) is extremely common in web development.

Angular utilizes the *ngFor structural directive to easily loop through an array and generate HTML for each item.

Whenever your TypeScript array changes, Angular automatically updates the list on the screen!


The *ngFor Syntax

The syntax for *ngFor uses the phrase let item of items.

Here, items represents the array in your component, and item is the variable representing the current iteration.

You attach this directive directly to the element you wish to repeat.

*ngFor Example:

<h3>Available Courses:</h3>
<ul>
  <!-- Generates a new <li> tag for every single course in the array -->
  <li *ngFor="let course of coursesArray">
    {{ course.title }}
  </li>
</ul>

Getting the Index

Sometimes you need to know the exact position (index) of the item inside the loop.

Angular allows you to capture the index by appending ; let i = index to the directive string.

This creates a variable i that you can output or use in your logic!

*ngFor Index Example:

<div *ngFor="let user of users; let i = index">
  <p>Rank #{{ i + 1 }}: {{ user.name }}</p>
</div>

Note: Remember that JavaScript arrays are zero-indexed, meaning the first item will have an index of 0.


Advanced Tracking: trackBy

By default, if you modify the underlying array (like deleting or reordering items), Angular will destroy and re-render the entire DOM list.

For massive lists, this causes significant performance lag and forces the browser to work extremely hard.

To optimize performance, you can implement a trackBy function in your component.

This tells Angular exactly which unique ID represents each item, allowing it to precisely update only the single DOM element that changed!

Performance trackBy Example:

<!-- Only elements with a changed ID will be re-rendered -->
<li *ngFor="let item of items; trackBy: trackItemById">
  {{ item.name }}
</li>

Exercise 1 of 2

?

Which syntax is correct for iterating through an array named 'students'?

Exercise 2 of 2

?

What is the purpose of using a trackBy function alongside an *ngFor loop?