Submit the Update Form
Chapter Objectives
- ✔️Submit the Update FormLearn how to submit an update form in an Angular application.
Update the Task with TaskService
The TaskService already includes a function to add a new task to the list. Let’s add a new function to update an existing task in the list.
🎓 Instructions
-
Update the file
src/app/task-service.ts
.import { Injectable } from "@angular/core";import { Task } from "./task.model";@Injectable({providedIn: "root",})export class TaskService {tasks: Task[] = [{title: "Task 1",description: "Description of task 1",createdAt: new Date(),},{title: "Task 2",description: "Description of task 2",createdAt: new Date(),},];addTask(task: Task) {this.tasks.push({...task,createdAt: new Date(),});}getTask(id: string) {return this.tasks.find((task) => task.id === id);}updateTask(task: Task) {const index = this.tasks.findIndex((t) => t.id === task.id);this.tasks[index] = task;}}
Update the TaskFormComponent
The TaskFormComponent is currently used to add a new task to the list.
Handle the update action through the form without creating a new task. To do this, keep the same submit function but update it to use the updateTask function from the TaskService.
When?
- If the task has an id, call the updateTask function.
- If the task doesn’t have an id, call the addTask function.
submit() { const id = this.route.snapshot.paramMap.get('id');
if (id) { const existingTask = this.taskService.getTask(id); this.taskService.updateTask({ ...existingTask, ...this.task }); } else { this.taskService.addTask(this.task); } this.router.navigate(['/']); }
In both cases, return to the task list.
🎓 Instructions
-
Update the file
src/app/task-form/task-form.component.ts
.import { Component, OnInit } from "@angular/core";import { ActivatedRoute } from "@angular/router";import { TaskService } from "../task.service";import { Task } from "../task.model";@Component({selector: "app-task-form",templateUrl: "./task-form.component.html",styleUrls: ["./task-form.component.css"],})export class TaskFormComponent implements OnInit {task: TaskForm = {title: "",description: "",};constructor(private route: ActivatedRoute,private taskService: TaskService) {}ngOnInit() {const id = this.route.snapshot.paramMap.get("id");if (id) {this.task = this.taskService.getTask(id);}}submit() {const id = this.route.snapshot.paramMap.get("id");if (id) {const existingTask = this.taskService.getTask(id);this.taskService.updateTask({...existingTask,...this.task,});} else {this.taskService.addTask(this.task);}this.router.navigate(["/"]);}}
Test it
- Click the
Update
button next to a task in the list. - Update the form with the new task details.
- Click the
Update Task
button. - The task should be updated in the list.
✔️ What you’ve learned
In this chapter, you learned how to update the TaskFormComponent to handle both updating and creating tasks.