Update TaskFormComponent
Chapter Objectives
- ✔️Fill the form with existing dataLearn how to populate a form with existing task data.
You can now access the TaskFormComponent by clicking the Update
link.
This path includes a dynamic value to pass the id of the task to update.
The TaskFormComponent form is currently empty because it was created to add a new task and is therefore initialized as an empty form.
task = { id: "", title: "", description: "",};
Update it to use the form for both creating and updating a task.
Retrieve task information to update with TaskService
Before getting the route identifier, let’s prepare the logic to identify the task to update. Since the task list is stored in TaskService, you’ll add a new function to retrieve a task based on its id. From this identifier, you’ll get the task to fill the form.
🎓 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): void {this.tasks.push({...task,createdAt: new Date(),});}getTask(id: string): Task {return this.tasks.find((task) => task.id === id)!;}}
Get the task identifier from the route
The id is present in the route path, you need to retrieve it in the TaskFormComponent. Use the ActivatedRoute service to get the id from the route.
This service provides access to information about the current route. As you did with the Router, you’ll inject it into the TaskFormComponent constructor.
Hooks: Angular lifecycle
Until now, you’ve initialized class properties during their declaration.
For example, you initialized the task property with an empty object:
task = { id: "", title: "", description: "",};
You can’t use such logic to initialize the task property with the task to update because this id
isn’t yet available when the Component class is created.
Why?
From creation to destruction, a component goes through several stages. When creating the Component class, route information is not yet available.
To handle such a case, Angular provides lifecycle hooks. Lifecycle hooks are methods that Angular calls in components and directives when it creates, changes, and destroys them.
One of the most used lifecycle hooks is ngOnInit, which is already present in all created components of the application. This hook is called right after Angular has instantiated the Component class. And at this point, the component is able to read route information.
Inside this hook, start by retrieving the route identifier.
ngOnInit() { const id = this.route.snapshot.paramMap.get('id');}
route.snapshot is a static image of route information and exposes a paramMap property.
This paramMap is a map of required and optional parameters specific to the route, including the dynamic route path parameters. The get method of the paramMap object allows us to retrieve the value of a parameter based on the name you used in the route path definition: id.
Then, you’ll retrieve the task to update from the TaskService based on the id available in the route.
ngOnInit() { const id = this.route.snapshot.paramMap.get('id'); this.task = this.taskService.getTask(id); }
ngOnInit() { const id = this.route.snapshot.paramMap.get('id');
if (id) { this.task = this.taskService.getTask(id); }}
🎓 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";@Component({selector: "app-task-form",templateUrl: "./task-form.component.html",styleUrls: ["./task-form.component.css"],})export class TaskFormComponent implements OnInit {task = {id: "",title: "",description: "",};constructor(private taskService: TaskService,private router: Router,private route: ActivatedRoute) {}ngOnInit() {const id = this.route.snapshot.paramMap.get("id");if (id) {this.task = this.taskService.getTask(id);}}}
Test it
- Click the
Update
button next to a task in the list. 2. The form should be filled with the task to update.
✔️ What you’ve learned
In this chapter, you learned how to update TaskFormComponent to fill the form with the task to update. You learned how to retrieve the task from TaskService based on the id available in the route.