# CRUD Operations
# 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.
Add a
saveTask
method to save the state of a task to the backend databasesrc/app/todo/todo.component.ts
async saveTask(task: Task) { const savedTask = await this.taskRepo.save(task); this.tasks = this.tasks.map(t => t === task ? savedTask : t); }
Why update the task array after saving a task?
Remult's
Repository.save
method issues either aPUT
or aPOST
request, depending on the existence of anid
value in theTask
object.In the next section of the tutorial, we'll add new tasks to the list by creating
Task
objects and saving them using the samesaveTask
function. So, to make sure a newly created task is onlyPOST
-ed once, we must replace it with the return value ofRepository.save
, which contains anid
.Modify the contents of the
tasks
div to include the followinginput
elements and a Save button to call thesaveTask
method.src/app/todo/todo.component.html
<input type="checkbox" [(ngModel)]="hideCompleted" (change)="fetchTasks()" > Hide Completed <main> <div *ngFor="let task of tasks"> <input type="checkbox" [(ngModel)]="task.completed" > <input [(ngModel)]="task.title"> <button (click)="saveTask(task)">Save</button> </div> </main>
Make some changes and refresh the browser to verify the backend database is updated.
# Add New Tasks
- Add the following
addTask
method to theTodoComponent
class:
src/app/todo/todo.component.ts
addTask() {
this.tasks.push(new Task());
}
- Add an Add Task button in the html template:
src/app/todo/todo.component.html
<input
type="checkbox"
[(ngModel)]="hideCompleted"
(change)="fetchTasks()"
>
Hide Completed
<main>
<div *ngFor="let task of tasks">
<input
type="checkbox"
[(ngModel)]="task.completed"
>
<input [(ngModel)]="task.title">
<button (click)="saveTask(task)">Save</button>
</div>
</main>
<button (click)="addTask()">Add Task</button>
Add a few tasks 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.
- Add the following
deleteTask
method to theTodoComponent
class:
src/app/todo/todo.component.ts
async deleteTask(task: Task) {
await this.taskRepo.delete(task);
this.tasks = this.tasks.filter(t => t !== task);
}
- Add a Delete button in the html:
src/app/todo/todo.component.html
<input
type="checkbox"
[(ngModel)]="hideCompleted"
(change)="fetchTasks()"
>
Hide Completed
<main>
<div *ngFor="let task of tasks">
<input
type="checkbox"
[(ngModel)]="task.completed"
>
<input [(ngModel)]="task.title">
<button (click)="saveTask(task)">Save</button>
<button (click)="deleteTask(task)">Delete</button>
</div>
</main>
<button (click)="addTask()">Add Task</button>