Display a list of tasks
- ✔️Discover *ngFor directiveLearn how to iterate over a list of items in a HTML template file using the *ngFor directive.
HTML structure
To display a list of items, the expected HTML structure is:
However, what happens if you want to display a dynamic list of items changing over time? What if a new task is added?
You want to rely on the tasks variable to display the proper list of tasks. If the tasks is updated, the view should be updated as well.
Angular Directives
Angular Components are Angular Directives with a HTML template. The goal of a Directive is not to display content but to manipulate the html content of an Angular component. They can help to dynamically hide/display some content, change their style, or affect how many times a content is displayed.
*ngFor directive
*ngFor name refers to for loop: its goal is to display a given html tag as many times as there are items in a provided list. You can apply it on any html tag. It’ll affect this tag and its children.
To use it, add this *ngFor on the html tag and provide it an arbitrary syntax to define the list you want to iterate over and a reference to use the value of each item.
This syntax is let task of tasks
:
- tasks refers to the list defined in your component.ts file.
- task is the reference to use the value of each item in the list (you can name it as you want).
🎓 Instructions
-
Update the
src/app/task-list.component.html
file. -
Go back to your browser and see the following page:
// TODO: Add image
Your list is now displayed in the browser. You should see Task repeated as many times (2) as there are tasks in the list.
✔️ What you learned
In this chapter, you learned how to use a list of items defined in your component.ts file towards the component.html file. You used the *ngFor directive to loop through the list of items and display them in the view. Such a task is quite common in web development, and you’ll likely use it in many of your Angular applications.
🚦 Quiz
What is the expected *ngFor directive syntax?
- *ngFor=“let task on tasks”
- *ngFor=“let task of tasks”
- *ngFor=“let task in tasks”
- *ngFor=“task of tasks”