Skip to content

Display a list of tasks

  • βœ”οΈ
    Discover *ngFor directive
    Learn 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:

<ul class="list-group">
<li class="list-group-item">Item 1</li>
<li class="list-group-item">Item 2</li>
<li class="list-group-item">Item 3</li>
</ul>
A bird sitting on a nest of eggs.

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).
<ul>
<li *ngFor="let item of items"></li>
</ul>

πŸŽ“ Instructions

  1. Update the src/app/task-list.component.html file.

    task-list.component.html
    <ul class="list-group">
    <li *ngFor="let task of tasks" class="list-group-item">
    Task
    </li>
    </ul>
  2. 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?

  1. *ngFor=β€œlet task on tasks”
  2. *ngFor=β€œlet task of tasks”
  3. *ngFor=β€œlet task in tasks”
  4. *ngFor=β€œtask of tasks”

πŸ”— Resources