Skip to content

Update TaskFormComponent

  • โœ”๏ธ
    Populate a form
    Learn how to populate a form with the task to update.

You are now able to land on the TaskFormComponent by clicking on the โ€˜Updateโ€™ link. This path includes a dynamic value to pass the id of the task to update.

The TaskFormComponent form is currently empty as it was created to add a new task, initialized as an empty form.

task-form.component.ts
task = {
id: '',
title: '',
description: ''
};

Letโ€™s update it to use the form both to create and update a task.

Retrieve the task to update with the TaskService

Before retrieving the id from the route, letโ€™s prepare the logic to identify the task to update. As the list of tasks is stored in the TaskService, youโ€™ll add a new function to retrieve a task based on its id. From this id, you will retrieve the task to fill the form.

๐ŸŽ“ Instructions

  1. Update the src/app/task-service.ts file.

    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);
    }
    }

Retrieve the task id from the route

The id is present in the route path, you need to retrieve it in the TaskFormComponent component. Use the ActivatedRoute service to retrieve the id from the route.

This service provides access to information about the current route. Like you did with the Router, youโ€™ll inject it in the constructor of the TaskFormComponent.

Angular lifecycle hooks

So far you initialized class properties when declaring them.

For example, you initialized the task property with an empty object:

task = {
id: '',
title: '',
description: ''
};

You cannot use such a logic to initialize the task property with the task to update because this idis not yet available when the Component class is created.

Why so?

From its creation to its destruction, a component goes through several stages.
At the class creation of the Component stage, the route information is not available yet.

To handle such a case, Angular provides lifecycle hooks. Lifecycle hooks are methods that Angular calls on components and directives as it creates, changes, and destroys them.

One of the most used lifecycle hooks is ngOnInit, itโ€™s already present in all the created Components of the application. This hook is called just after Angular instantiated the Component class. And at that time, the component is able to read the route information.

Inside this hook, start by retrieving the id from the route.

ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
}

The route.snapshot is a static image of the route information and it exposes a paramMap property.

This paramMap is a map of the required and optional parameters specific to the route, including 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.

Next, 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

  1. Update the src/app/task-form/task-form.component.ts file.

    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 route: ActivatedRoute) {
    }
    ngOnInit() {
    const id = this.route.snapshot.paramMap.get('id');
    if (id) {
    this.task = this.taskService.getTask(id);
    }
    }
    }

Letโ€™s test it out

  1. Click on the โ€˜Updateโ€™ button next to a task in the list.
  2. The form should be populated with the task to update.

โœ”๏ธ What you learned

In this chapter, you learned how to update the TaskFormComponent to populate the form with the task to update. You learned how to retrieve the task to update from the TaskService based on the id available in the route.