Sub topic 5
Splitting out a task item with input() and output()
In the previous chapter, TaskListComponent rendered each row itself. That works, but the list component now owns the markup for one task, the checkbox wiring, and the delete button. In this chapter you move that markup into TaskItemComponent. The item receives its data through input() and reports user actions through output().
This chapter assumes you have the Task interface, TaskService, and a standalone TaskListComponent from the earlier chapters. It also assumes you know the basics of signals (signal() and computed()). Everything here uses the signal-based input() and output() functions, which replace the older @Input() and @Output() decorators.
The one-way contract
A parent and child communicate in two directions with two different mechanisms.
- Data flows down. The parent binds a value to a property of the child with
[task]="task". The child reads it. - Events flow up. The child emits a value. The parent listens with
(toggled)="..."and decides what to do.
The child never changes the task itself. It only announces "the user toggled task 3". The parent, which has access to TaskService, performs the state change. This keeps the item component presentational: it needs no service, and you can reuse it anywhere that can supply a Task and handle two events.
The item component
Here is the child component.
import { Component, input, output } from '@angular/core';
import { Task } from './task';
@Component({
selector: 'app-task-item',
template: `
<input type="checkbox" [checked]="task().done" (change)="toggled.emit(task().id)" />
<span>{{ task().title }}</span>
<button type="button" (click)="removed.emit(task().id)">Delete</button>
`,
})
export class TaskItemComponent {
readonly task = input.required<Task>();
readonly toggled = output<number>();
readonly removed = output<number>();
}Reading an input
input.required<Task>() returns a read-only signal of type InputSignal<Task>. You read it by calling it: task(). Because it is a signal, templates and computed() values that read it update automatically when the parent passes a new object.
Two consequences follow:
- You cannot assign to
task. It has nosetmethod. Only the parent's binding changes it. - You cannot read it too early. The value is not available while the constructor runs, because Angular sets inputs after creating the instance. Reading a required input before then throws a runtime error (NG0950). Do derived work in
computed()or in a template, not in the constructor.
Emitting from an output
output<number>() creates an OutputEmitterRef<number>. Calling .emit(value) delivers the value to every listener in the parent. The type argument is checked: toggled.emit('a') fails to compile.
Outputs are not DOM events. They do not bubble up the DOM tree, and only the direct parent template can listen to them. That is why the parent must bind (toggled) on the <app-task-item> element itself.
Wiring the item into the list
Update TaskListComponent to use the new component. Note the new imports array. A standalone component can only use other components that it lists there.
import { Component, inject } from '@angular/core';
import { TaskItemComponent } from './task-item.component';
import { TaskService } from './task.service';
@Component({
selector: 'app-task-list',
imports: [TaskItemComponent],
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>
<app-task-item
[task]="task"
(toggled)="toggle($event)"
(removed)="remove($event)"
/>
</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);
}
}Three details are worth checking.
$eventinside(toggled)="toggle($event)"is the value passed toemit(). Here that is the task id, anumber. For a native DOM event,$eventwould be the event object. For an output, it is your payload.- The
<li>stays in the parent. A custom element such as<app-task-item>is not a valid child of<ul>, so the list keeps the<li>wrapper and the item fills it. - The
track task.idexpression still lives in the parent. It tells Angular which item component instance belongs to which task, so a reordered or filtered list reuses instances instead of rebuilding them.
Why the service uses immutable updates
When the user toggles a task, TaskService.toggle replaces the matching object with { ...t, done: !t.done }. The @for loop then passes the new object to the item's task input, and the input signal changes.
If the service mutated the object in place (t.done = !t.done), the reference would be the same. The input signal compares values by reference (Object.is), so it would not notify, and a child that reads only task() might not update when it should. Immutable updates are what make signal inputs reliable. Treat any object you receive through an input as read-only.
Optional inputs, defaults, and transforms
input.required is right for task, because an item without a task makes no sense. For optional configuration, give a default value instead.
import { booleanAttribute, Component, computed, input, output } from '@angular/core';
@Component({
selector: 'app-badge',
template: `
<button type="button" [disabled]="disabled()" (click)="pressed.emit()">
{{ label() }}
</button>
<small>{{ summary() }}</small>
`,
})
export class BadgeComponent {
readonly label = input('Press');
readonly disabled = input(false, { transform: booleanAttribute });
readonly pressed = output<void>();
readonly summary = computed(() => `${this.label()} (${this.disabled() ? 'off' : 'on'})`);
}input('Press')infersInputSignal<string>and uses'Press'when the parent does not bind the property.transform: booleanAttributeconverts the incoming value before it reaches the signal. With it,<app-badge disabled />setstrue, where a plain input would receive the empty string''.output<void>()is for events with no payload. Callpressed.emit()with no arguments.computed()can safely depend on inputs. It re-evaluates wheneverlabel()ordisabled()changes.
You can also rename an input or output for the outside world with input(0, { alias: 'count' }). Use aliases sparingly. They make the template name differ from the class property name, which makes code harder to search.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `Can't bind to 'task' since it isn't a known property of 'app-task-item'` | The parent does not list `TaskItemComponent` in `imports` | Add it to the parent's `imports` array |
| `'app-task-item' is not a known element` | Same missing import, or a wrong `selector` string | Import the component and match the selector |
| NG0950 when reading `task()` | A required input was read in the constructor or a field initializer | Read it in a template, a `computed()`, or a lifecycle hook such as `ngOnInit` |
| `(toggled)` handler never runs | The event name does not match the output property, or `emit()` is never called | Use the property name exactly: `toggled` |
| Compile error: `Required input 'task' from component TaskItemComponent must be specified` | The parent omitted the `[task]` binding | Bind `[task]="..."` |
| Item does not update after a change | The parent mutated the task object in place | Replace the object, as `TaskService` does |
Testing the split
Because the item has no dependencies, you can test it by creating it with TestBed and setting its input through fixture.componentRef.setInput('task', { id: 1, title: 'Write tests', done: false }). Then you click the delete button and subscribe to removed to check the emitted id. You do not need TaskService at all. That is a practical benefit of the split.
Summary of the pattern
- A presentational child declares what it needs (
input) and what it can report (output). - The parent owns state and decides what each event means.
- Data passed down is treated as read-only, and updates replace objects.
- Standalone components must be listed in the consumer's
imports.
Exercise
You add a "Rename" feature. The item shows a text box with the current title, and when the user presses Enter, the parent should save the new title. Which input and output declarations would you add to TaskItemComponent, and why can't the child simply assign the new title to task().title?
Show answer
Keep task = input.required<Task>() and add an output that carries both the id and the new title, for example renamed = output<{ id: number; title: string }>(). On Enter, call renamed.emit({ id: task().id, title: newTitle }). The child cannot assign to task().title because the input is a read-only signal whose value belongs to the parent and the service. Mutating the object in place would bypass the service, would not change the object reference, and could leave other parts of the app out of sync. The parent handles (renamed) by calling a new TaskService.rename(id, title) method that replaces the task immutably.
Exercise
A teammate writes readonly doubled = this.count() * 2; as a field in a component with count = input.required<number>(). What goes wrong, and what is the fix?
Show answer
The field initializer runs when the instance is constructed, before Angular has set the input, so reading count() throws a required-input error (NG0950). Even for an optional input, the value computed would be a one-time snapshot that never updates. The fix is readonly doubled = computed(() => this.count() * 2);, which reads the input lazily and recalculates whenever it changes.