Skip to content

Add a route for the task update feature

Chapter Objectives

  • โœ”๏ธ
    Create a dynamic route
    Define a dynamic routing path to pass the ID of the task to update.

Route Configuration

So far, you have defined 2 route paths:

  • '' for the TaskListComponent to display the list of tasks
  • 'add-task' for the AddTaskComponent to display a form

The update path is quite different because you donโ€™t just want to go to a new page. To update a task, you need to know which task to update.

A common way to provide information to a routed component is to use a dynamic routing path.

Create the Route

The new path will be update/:id. The update part is static but the :id part is dynamic.

You wonโ€™t create a dedicated component for the update functionality. The purpose of TaskFormComponent is to create tasks with user input and update them. Letโ€™s update the component to handle both creation and updating.

๐ŸŽ“ Instructions

  1. Update the file src/app/app-routing.module.ts.

    import { NgModule } from "@angular/core";
    import { RouterModule, Routes } from "@angular/router";
    import { TaskListComponent } from "./task-list/task-list.component";
    import { TaskFormComponent } from "./task-form/task-form.component";
    const routes: Routes = [
    { path: "", component: TaskListComponent },
    { path: "add-task", component: TaskFormComponent },
    { path: "update/:id", component: TaskFormComponent },
    ];
    @NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule],
    })
    export class AppRoutingModule {}

Update the Navigation

Add a link in the TaskListComponent to access the TaskFormComponent with the id of the task to update. By accessing this path, you will extract the id value from the URL in the next chapter.

๐ŸŽ“ Instructions

  1. Update the file src/app/task-list/task-list.component.html.

    <tr *ngFor="let task of tasks">
    <td>{{ task.title }}</td>
    <td>{{ task.createdAt | date }}</td>
    <td>
    <a class="btn btn-primary" [routerLink]="['/update', task.id]">Update</a>
    </td>
    </tr>

The routerLink value expects a string or an array of URL segments. The first is a string, the static part of the path. The second is the id of the task to update.

Test it

  1. Click the โ€˜Updateโ€™ button on the first task in the list.
  2. Check the URL: http://localhost:4200/update/d8ecfcda-ef70-420f-8236-3138ff64ac9f for example.
  3. The TaskFormComponent form is displayed correctly.

โœ”๏ธ What you have learned

In this chapter, you learned how to add a route to update a task in an Angular application. You learned how to define a dynamic routing path to pass the id of the task to update. You also learned how to use the routerLink directive to access the TaskFormComponent and pass the id of the task to update.