Sub topic 3
Adding a Task Detail Route
Assume you know basic Angular components, TypeScript interfaces, dependency injection, signals, and standalone component imports. This chapter connects a detail view to HTTP data, tests, change detection, and a production build.
Adding the route
Define a parameterized route. The :id segment captures a task identifier.
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: '' },
];A detail component can receive the route value through component input binding:
import { Component, input } from '@angular/core';
@Component({
standalone: true,
template: `<p>Task ID: {{ id() }}</p>`,
})
export class TaskDetailComponent {
readonly id = input.required<string>();
}Register withComponentInputBinding() when configuring the router. A link such as /tasks/3 then supplies "3" to id.
Observables and HTTP
An Observable represents a sequence of values that can arrive over time. RxJS is the library Angular uses for composing these sequences. An HTTP method returns an Observable, but the request normally starts only when something subscribes.
getTasks(): Observable<Task[]> {
return this.http.get<Task[]>('/api/tasks');
}Use the result in a component with a subscription, an async pipe, or conversion to a signal. Unsubscribe from long-lived streams, or use Angular patterns that manage cleanup automatically.
Saving and testing
Wrap HttpClient calls in an injectable API service. Keep URL and response types in that service. Components should coordinate UI state rather than construct requests.
Test state changes through TestBed:
const service = TestBed.inject(TaskService);
service.add('Write tests');
const id = service.tasks()[0].id;
service.toggle(id);
expect(service.tasks()[0].done).toBe(true);
expect(service.remaining()).toBe(0);Change detection and production builds
OnPush change detection lets Angular check a component when an input changes, an event runs, or a signal read by its template changes. Prefer immutable updates, such as replacing an array with [...]. This makes changes visible and avoids hidden mutations.
Run the checks and production build with the CLI:
ng test
ng buildThe build output is optimized for deployment. Configure the server to serve the application’s entry page for client-side routes such as /tasks/3.
Exercise
Why should a task update replace the task array instead of mutating an item in place?
Show answer
Replacing the array gives Angular a new reference and works predictably with OnPush change detection.