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.
// 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.
<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.
// 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.
<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).
<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?
✍️ Practice
- Render a list of your three favourite movies with
*ngFor. - Loop over an array of student objects and show each name and grade.
🏠 Homework
- Show a numbered to-do list from an array of task objects, displaying the title and whether each is done.