Skip to content

CRUD Operations

Adding new tasks

Now that we can see the list of tasks, it's time to add a few more.

  1. Add a newTaskTitle field and an addTask method to the ToDoComponent
ts
// src/app/todo/todo.component.ts

export class TodoComponent implements OnInit {
  newTaskTitle = ""
  async addTask() {
    try {
      const newTask = await this.taskRepo.insert({ title: this.newTaskTitle })
      this.tasks.push(newTask)
      this.newTaskTitle = ""
    } catch (error: any) {
      alert(error.message)
    }
  }
}
  • the call to taskRepo.insert will make a post request to the server, insert the new task to the db, and return the new Task object with all it's info (including the id generated by the database)
  1. Add an Add Task form in the html template:
html
<!-- src/app/todo/todo.component.html -->

<h1>todos</h1>
<main>
  <form (submit)="addTask()">
    <input
      placeholder="What needs to be done?"
      [(ngModel)]="newTaskTitle"
      name="newTaskTitle"
    />
    <button>Add</button>
  </form>
  <div *ngFor="let task of tasks">
    <input type="checkbox" [(ngModel)]="task.completed" />
    {{ task.title }}
  </div>
</main>

Try adding a few tasks to see how it works

Rename Tasks and Mark as Completed

To make the tasks in the list updatable, we'll bind the input elements to the Task properties and add a Save button to save the changes to the backend database.

  1. Add a saveTask method to save the state of a task to the backend database

    ts
    // src/app/todo/todo.component.ts
    
    async saveTask(task: Task) {
      try {
        await this.taskRepo.save(task)
      } catch (error: any) {
        alert(error.message)
      }
    }
  1. Modify the contents of the tasks div to include the following input elements and a Save button to call the saveTask method.

    html
    <!-- src/app/todo/todo.component.html -->
    
    <div *ngFor="let task of tasks">
      <input
        type="checkbox"
        [(ngModel)]="task.completed"
        (change)="saveTask(task)"
      />
      <input [(ngModel)]="task.title" />
      <button (click)="saveTask(task)">Save</button>
    </div>

Make some changes and refresh the browser to verify the backend database is updated.

Delete Tasks

Let's add a Delete button next to the Save button of each task in the list.

  1. Add the following deleteTask method to the TodoComponent class:
ts
// src/app/todo/todo.component.ts

async deleteTask(task: Task) {
   await this.taskRepo.delete(task);
   this.tasks = this.tasks.filter(t => t !== task);
}
  1. Add a Delete button in the html:
html
<!-- src/app/todo/todo.component.html -->

<div *ngFor="let task of tasks">
  <input
    type="checkbox"
    [(ngModel)]="task.completed"
    (change)="saveTask(task)"
  />
  <input [(ngModel)]="task.title" />
  <button (click)="saveTask(task)">Save</button>
  <button (click)="deleteTask(task)">Delete</button>
</div>

MIT Licensed | Made by the Remult team with ❤️