Update Task Route
- Configure update route
Set up routing for the task update functionality.
- Handle route parameters
Learn how to pass and retrieve task ID in routes.
- Implement route guards
Add protection to ensure valid task updates.
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.
The :id
part is a route parameter. You can chain multiple route parameters
in a path, for example 'update/:id/:name'
. Each is prefixed with a colon :
followed by an arbitrarily chosen name.
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.
-
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.
-
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. In our situation, the routerLink value is an array of two elements:
/update
is a string, the static part of the path.task.id
is the dynamic part of the path, the id of the task to update.
Test it
-
Click the ‘Update’ link on the first task in the list.
-
Check the URL:
http://localhost:4200/update/d8ecfcda-ef70-420f-8236-3138ff64ac9f
for example. -
The TaskFormComponent form is displayed correctly.
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.