Sub topic 9
Adding a task detail route
This chapter adds a second screen to the task list app. The list stays at /, and each task gets its own page at /tasks/:id. You will configure routes, render them in the root component, link to them from the list, and read the route parameter in a component. You will also handle a task that does not exist.
I assume you have the TaskService from the earlier chapters, with its tasks signal and remove() method. You should also be comfortable with standalone components and input().
How the router fits together
The Angular router has four parts, and each has one job:
| Piece | Job |
|---|---|
| `Routes` array | Maps URL paths to components |
| `provideRouter()` | Registers the router in the application config |
| `<router-outlet />` | Marks where the matched component renders |
| `routerLink` / `Router` | Triggers navigation from a template or from code |
When the URL changes, the router walks the Routes array from top to bottom. It renders the first match inside the outlet.
Configuring the routes
The routes and the application config look like this:
// app.routes.ts
import { Routes } from '@angular/router';
import { TaskListComponent } from './task-list.component';
import { TaskDetailComponent } from './task-detail.component';
export const routes: Routes = [
{ path: '', component: TaskListComponent },
{ path: 'tasks/:id', component: TaskDetailComponent },
{ path: '**', redirectTo: '' },
];
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes, withComponentInputBinding()), provideHttpClient()],
};Three details matter here.
- Order is significant. The
'**'wildcard matches every URL, so it must be last. If you put it first, no other route is ever reached. :idis a route parameter. The colon marks a variable segment. The URL/tasks/3matches withidequal to'3'.withComponentInputBinding()is a feature flag. Without it, route parameters are not copied into component inputs. You would have to injectActivatedRouteand subscribe to itsparamMapinstead.
provideHttpClient() is already in the config for the HTTP chapter. It plays no part in routing.
Rendering the outlet
The router needs a place to put the matched component. Make your root component import RouterOutlet and place it in the template. The root class may be called App or AppComponent, depending on your CLI version. Keep your existing name.
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
@Component({
selector: 'app-root',
imports: [RouterOutlet],
template: `
<h1>Tasks</h1>
<router-outlet />
`,
})
export class App {}Standalone components do not inherit imports from a parent. Each component lists the directives it uses in its own imports array. Forgetting RouterOutlet is the most common reason a new route shows a blank page. The console reports that router-outlet is not a known element.
Linking from the list
Use routerLink instead of a plain href. A plain href makes the browser reload the page, which resets every signal in memory. routerLink navigates inside the running app and keeps the state.
Update TaskListComponent to import RouterLink and wrap each title in a link:
import { Component, inject } from '@angular/core';
import { RouterLink } from '@angular/router';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-list',
imports: [RouterLink],
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>
<input type="checkbox" [checked]="task.done" (change)="toggle(task.id)" />
<a [routerLink]="['/tasks', task.id]" [class.done]="task.done">{{ task.title }}</a>
<button type="button" (click)="remove(task.id)">Delete</button>
</li>
} @empty {
<li>No tasks yet.</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TaskListComponent {
private readonly service = inject(TaskService);
readonly tasks = this.service.tasks;
readonly remaining = this.service.remaining;
toggle(id: number): void {
this.service.toggle(id);
}
remove(id: number): void {
this.service.remove(id);
}
}The array form ['/tasks', task.id] builds the URL /tasks/3 from segments. The router encodes each segment for you, so this is safer than string concatenation. The leading / makes the link absolute, so it resolves the same way wherever the component is used.
Reading the parameter in the detail component
With withComponentInputBinding(), a route parameter named id is set on a component input named id. The router passes the raw URL text, so the input type is string, not number.
Create task-detail.component.ts:
import { Component, computed, inject, input } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-detail',
imports: [RouterLink],
template: `
@if (task(); as current) {
<h2>{{ current.title }}</h2>
<p>Status: {{ current.done ? 'Done' : 'Open' }}</p>
<button type="button" (click)="toggle(current.id)">
Mark as {{ current.done ? 'open' : 'done' }}
</button>
<button type="button" (click)="remove(current.id)">Delete</button>
} @else {
<p>Task not found.</p>
}
<a routerLink="/">Back to the list</a>
`,
})
export class TaskDetailComponent {
private readonly service = inject(TaskService);
private readonly router = inject(Router);
readonly id = input.required<string>();
readonly task = computed(() => {
const numericId = Number(this.id());
return this.service.tasks().find(t => t.id === numericId);
});
toggle(id: number): void {
this.service.toggle(id);
}
remove(id: number): void {
this.service.remove(id);
void this.router.navigateByUrl('/');
}
}Here is what each part does.
input.required<string>()declares the input. Its name must match the route parameter exactly, so:idbinds toid.computed()re-runs wheneverid()orservice.tasks()changes. The page therefore updates when you toggle the task here, and when the router moves to a different id.Number(this.id())converts the string. Comparingt.id === this.id()would never match, because3 === '3'is false in TypeScript's runtime semantics too.@if (task(); as current)stores the value in a local template variable. Inside the block,currentis known to be aTaskand notundefined.navigateByUrl('/')is programmatic navigation. It returns a promise that resolves when navigation finishes. Thevoidmarks that we choose not to wait for it.
Run ng serve, add a task, and click its title. The URL changes to /tasks/1, the list disappears, and the detail view appears. Use the browser back button to return. The router has pushed a history entry, so back and forward work without extra code.
Edge cases to handle
Unknown ids
Visiting /tasks/999 or /tasks/abc still matches the route. Number('abc') is NaN, which equals no task id. In both cases find() returns undefined, and the @else branch shows "Task not found." The component handles the missing task. The router does not treat this as an error.
State is lost on reload
The tasks live in a signal in memory. If you open /tasks/1 in a new tab, or press refresh, the app restarts with an empty list. The detail page then shows "Task not found." This is expected for now. The HTTP chapter fixes it by loading tasks from a backend.
Navigating between two ids
When the route changes from /tasks/1 to /tasks/2, Angular reuses the same TaskDetailComponent instance. It only updates the id input. Code that reads the parameter once in the constructor would show stale data. Because task is a computed() that depends on id(), it stays correct. This is the main reason to derive values from the input instead of copying them.
Required inputs without a parameter
input.required throws if nothing sets it. The tasks/:id path guarantees an id is always present, so it is safe here. Do not reuse this component under a route that lacks :id unless you switch to input<string>() and handle undefined.
Common errors
| Symptom | Likely cause |
|---|---|
| Blank page after a link click | `RouterOutlet` missing from the root component's `imports` |
| `routerLink` renders as plain text with no click effect | `RouterLink` missing from the component's `imports` |
| Detail page always says "not found" | Comparing the string `id` to a numeric task id without `Number()` |
| `NG0950` error about a required input | The route has no `:id` segment, or `withComponentInputBinding()` is missing |
| Every unknown URL shows the list, even valid ones | The `'**'` route is placed before the others |
Exercise
A user opens /tasks/2, then clicks a link that goes to /tasks/3. The same TaskDetailComponent instance is reused. Why does the page still show the right task, and what would break if the component read the id once in its constructor and stored the matching task in a plain field?
Show answer
The router updates the id input on the existing instance. The task value is a computed() that depends on id(), so it recalculates and the template updates. A plain field set in the constructor would run only once, so the page would keep showing task 2 after the URL changed to /tasks/3.
Exercise
Add a route for the path 'about' that renders a component named AboutComponent, and place it correctly relative to the existing routes. Where does it go in the array, and why?
Show answer
Add { path: 'about', component: AboutComponent } before the { path: '**', redirectTo: '' } entry, for example after the 'tasks/:id' route. The router uses the first match, and the wildcard matches every URL, so any route placed after it would never be reached.