Angular Labs
COOKIES

Handle an Empty List

Git diff Branch
Chapter Objectives
  • Handle an empty list

    Learn how to handle an empty task list in your Angular application.

You’ve just learned how to delete a task from the list, now you want to display a message when the list is empty.

The @if Controlf Flow syntax

To iterate over the task list, you used @for from the Control Flow feature.

Another feature from the Control Flow is the @if directive. It allows you to condition the display of an element in the view.

By giving it a condition, the element is only displayed if the condition is true.

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

    @for (task of tasks; track task.id) {
    <tr>
    <td>{{ task.title }}</td>
    <td>{{ task.createdAt | date }}</td>
    <td>
    <a class="btn btn-primary" [routerLink]="['/update', task.id]">Update</a>
    <button
    class="btn btn-danger"
    type="button"
    (click)="deleteTask(task.id)"
    >
    Delete
    </button>
    </td>
    </tr>
    }
    @if (!tasks.length) {
    <p>No tasks</p>
    }

Let’s test it!

  1. Delete all tasks from the list.
  2. The message “No tasks” should appear.
What you've learned

In this chapter, you learned how to use the *ngIf directive.