Skip to content

Display a message when the list is empty

Chapter Objectives

  • ✔️
    Display conditional HTML content
    Learn how to use the *ngIf directive to display conditional HTML content.

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 *ngIf directive

To iterate over the task list, you used the *ngFor directive. This is a structural directive: it allows you to add, remove, or manipulate DOM elements.

Another structural directive is the *ngIf directive. It allows you to condition the display of an element in the view.

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

🎓 Instructions

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

    <tr *ngFor="let task of tasks">
    <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>
    <p *ngIf="!tasks.length">No tasks</p>

Let’s test it!

  1. Delete all tasks from the list.
  2. The message “No tasks” should appear.

✔️ What you have learned

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