Templates & LogicCore· 35 min read

Lists with *ngFor

Loop over an array and render one element per item — the way you show lists in Angular.

What you will learn

  • Render a list with *ngFor
  • Show each item’s data with interpolation
  • Get the index of each item

One element per item

*ngFor repeats an element once for every item in an array. It is how you turn a list of data into a list on the screen.

An array to loop over
// component class
fruits = ['Apple', 'Banana', 'Mango'];

Note: Output: (No visible output by itself.) This is a plain array of three strings. On its own it shows nothing — the template below turns it into a list on the screen.

*ngFor renders one <li> per fruit
<ul>
  <li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>

Note: Output: • Apple • Banana • Mango Angular creates one <li> for each item. let fruit of fruits means “give me each item, one at a time, and call it fruit.” Add an item to the array and a new <li> appears.

Looping over objects

Real lists are usually objects. Loop the same way and read each property.

An array of task objects
// component class
tasks = [
  { title: 'Buy milk', done: false },
  { title: 'Walk dog', done: true }
];

Note: Output: (No visible output by itself.) Now each item is an object with a title and a done flag. The template below loops over them and reads both properties out of each object.

Read each object’s properties inside the loop
<ul>
  <li *ngFor="let task of tasks">
    {{ task.title }} — {{ task.done ? 'done' : 'pending' }}
  </li>
</ul>

Note: Output: • Buy milk — pending • Walk dog — done For each task object Angular prints its title and uses a small expression to show “done” or “pending”.

Getting the position number

Need the item’s number? Capture the index (it starts at 0).

Capture the index to number your list
<li *ngFor="let fruit of fruits; let i = index">
  {{ i + 1 }}. {{ fruit }}
</li>

Note: Output: 1. Apple 2. Banana 3. Mango The index starts at 0, so we print i + 1 to number the list from one.

Tip: For long lists that change often, add trackBy so Angular updates only the rows that changed instead of rebuilding the whole list. It is a performance booster you will meet as your apps grow.

Q. What does *ngFor="let item of items" do?

Answer: *ngFor loops over the array and renders the element one time per item, giving you each item in the loop variable.

✍️ Practice

  1. Render a list of your three favourite movies with *ngFor.
  2. Loop over an array of student objects and show each name and grade.

🏠 Homework

  1. Show a numbered to-do list from an array of task objects, displaying the title and whether each is done.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →