Skip to content

Add route for update task feature

  • ✔️
    Create a dynamic route
    Define a dynamic route path to pass the id of the task to update.

The route path

So far you defined 2 route paths:

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

The update route path is quite different as you don’t just want to land on a new page: to update a task, you need to know which task to update.

A common way to provide an information to a routed component is by using a dynamic route 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 feature. The purpose of the TaskFormComponent is to create tasks with user input: let’s update it to handle both creation and update.

🎓 Instructions

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

    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 { }

Let’s add a link to the TaskListComponent to navigate to the TaskFormComponent with the id of the task to update. By navigating to this path, you will extract the id value from the URL in the next chapter.

🎓 Instructions

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

    <ul>
    <li *ngFor="let task of tasks; let i = index">
    Task name: {{ task.title }}
    <a [routerLink]="['/update', task.id]">Update</a>
    </li>
    </ul>

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

Let’s test it out

  1. Click on the ‘Update’ button next to a task in the list.
  2. Check the URL: http://localhost:4200/update/1 for example.
  3. The TaskFormComponent should be displayed.

✔️ What you 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 route path to pass the id of the task to update. You also learned how to use the routerLink directive to navigate to the UpdateTaskComponent and pass the id of the task to update.