CRUD Operations
Adding new tasks
Now that we can see the list of tasks, it's time to add a few more.
- Add a
newTaskTitlefield and anaddTaskmethod to theToDoComponent
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.insertwill make a post request to the server, insert the new task to thedb, and return the newTaskobject with all it's info (including the id generated by the database)
- 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.
Add a
saveTaskmethod to save the state of a task to the backend databasets// src/app/todo/todo.component.ts async saveTask(task: Task) { try { await this.taskRepo.save(task) } catch (error: any) { alert(error.message) } }
Modify the contents of the
tasksdiv to include the followinginputelements and a Save button to call thesaveTaskmethod.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.
- Add the following
deleteTaskmethod to theTodoComponentclass:
ts
// 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:
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>