Sub topic 12
Passing Data Between Components
Real applications are trees of components. A parent component owns some state and hands pieces of it to children. Those children report user actions back up. Angular formalizes this with inputs, which carry data down, and outputs, which carry events up. It also has model inputs, which combine the two for two-way binding.
This chapter assumes you have read the earlier chapters on standalone components, template binding, and signals. You should already know how signal(), computed(), property binding [x], and event binding (x) work.
The Data-Down, Events-Up Model
A child component never reaches into its parent, and a parent never calls into a child's internals. The contract between them is the child's public API, which is its inputs and outputs. Because data flows one way, you can always answer two questions: "where does this value come from?" (the parent's binding) and "who reacts to this event?" (the parent's handler).
Declaring Inputs with input()
The input() function declares a property that a parent can bind to. It returns an InputSignal, so you read it by calling it, the same way you read any signal.
// src/app/todo-list.ts
import { Component, input, output } from '@angular/core';
@Component({
selector: 'app-todo-list',
template: `
@if (items().length === 0) {
<p>Nothing to do.</p>
} @else {
<ul>
@for (item of items(); track item) {
<li (click)="selected.emit(item)">{{ item }}</li>
}
</ul>
}
`,
})
export class TodoList {
items = input<string[]>([]);
selected = output<string>();
}The argument to input() is the default value. The child uses that value until the parent binds something. The generic type parameter, string[] here, is what the template type checker enforces on the parent's binding.
Input signals are read-only inside the child. You cannot call this.items.set(...). That restriction is deliberate: the parent owns the value. If the child needs to derive something from it, use computed():
import { Component, computed, input } from '@angular/core';
@Component({
selector: 'app-todo-summary',
template: `<p>{{ remaining() }} item(s) left</p>`,
})
export class TodoSummary {
items = input<string[]>([]);
remaining = computed(() => this.items().length);
}When the parent passes a new array, items() changes, remaining() recomputes, and the view updates. You need no lifecycle hook for this.
Declaring Outputs with output()
The output() function declares a custom event. It returns an OutputEmitterRef<T>, and you call .emit(value) on it. The type parameter fixes the payload type. In the example above, selected.emit(42) would be a compile error.
Outputs are not signals. They hold no current value; they only notify listeners when something happens.
Wiring the Parent
The parent must list the child in its imports array, then bind to the child's input and listen to its output:
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { TodoList } from './todo-list';
@Component({
selector: 'app-root',
imports: [TodoList],
template: `
<app-todo-list [items]="todos()" (selected)="onSelected($event)" />
<p>Last selected: {{ lastSelected() ?? 'none' }}</p>
<button (click)="addTodo()">Add todo</button>
`,
})
export class App {
todos = signal(['Buy milk', 'Write chapter', 'Ship app']);
lastSelected = signal<string | null>(null);
onSelected(item: string) {
this.lastSelected.set(item);
}
addTodo() {
this.todos.update((list) => [...list, `Task ${list.length + 1}`]);
}
}Three details matter here:
[items]="todos()"calls the parent's signal and passes the array value down.$eventin an output handler is the value passed toemit(). Its type isstringhere.addTodo()creates a new array instead of pushing into the old one. Signals compare values by reference, so a mutated array with the same reference does not notify consumers.
Required Inputs, Transforms and Aliases
input() takes options that cover the edge cases you will hit in shared components.
// src/app/badge.ts
import { Component, booleanAttribute, input, numberAttribute } from '@angular/core';
@Component({
selector: 'app-badge',
template: `
<span [class.muted]="disabled()" [attr.data-tone]="tone()">
{{ label() }} ({{ count() }})
</span>
`,
styles: `.muted { opacity: 0.5; }`,
})
export class Badge {
label = input.required<string>();
count = input(0, { transform: numberAttribute });
disabled = input(false, { transform: booleanAttribute });
tone = input('info', { alias: 'badgeTone' });
}You can then write this in a parent template that imports Badge:
<app-badge label="Inbox" count="3" disabled badgeTone="warning" />| Option | What it does | Edge case it solves |
|---|---|---|
| `input.required<T>()` | No default. The compiler errors if the parent omits the binding. | Prevents silently rendering `undefined`. |
| `transform: numberAttribute` | Converts the bound value to a number. | `count="3"` is a static string attribute. Without the transform it is a type error. |
| `transform: booleanAttribute` | Treats a bare attribute or `""` as `true`, and `"false"` as `false`. | Lets you write HTML-style `disabled` with no value. |
| `alias: 'badgeTone'` | The template uses a different name than the class property. | Avoids collisions with native attributes or keeps a public name stable while you rename internals. |
Static attributes such as label="Inbox" pass the literal string. Brackets such as [label]="title()" evaluate an expression. If you write [label]="Inbox", Angular looks for a property called Inbox on the parent, which is a common typo.
Two-Way Binding with model()
Some children both display a value and change it, for example a stepper, a toggle, or a custom text field. A model() input is writable inside the child, and Angular automatically pairs it with an output named after it plus Change.
// src/app/stepper.ts
import { Component, model } from '@angular/core';
@Component({
selector: 'app-stepper',
template: `
<button (click)="value.update((v) => v - 1)">-</button>
<span>{{ value() }}</span>
<button (click)="value.update((v) => v + 1)">+</button>
`,
})
export class Stepper {
value = model(0);
}// src/app/cart-line.ts
import { Component, signal } from '@angular/core';
import { Stepper } from './stepper';
@Component({
selector: 'app-cart-line',
imports: [Stepper],
template: `
<app-stepper [(value)]="quantity" />
<p>Quantity in parent: {{ quantity() }}</p>
`,
})
export class CartLine {
quantity = signal(1);
}Note that [(value)]="quantity" passes the signal itself without parentheses. Angular reads it to set the input and writes to it when the child emits valueChange. If you wrote [(value)]="quantity()" you would get a compile error, because a call result cannot be assigned to.
| API | Direction | Writable in child | Template syntax |
|---|---|---|---|
| `input()` | Parent to child | No | `[name]="expr"` |
| `output()` | Child to parent | Not applicable | `(name)="handler($event)"` |
| `model()` | Both | Yes | `[(name)]="signal"` |
Prefer input() plus output() when the parent should decide whether a change is accepted, for example when it validates first. Use model() when the child simply edits a value the parent wants to keep in sync.
Relationship to the Decorator APIs
Older code and many libraries use @Input() and @Output() with EventEmitter:
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({ selector: 'app-legacy-item', template: `{{ name }}` })
export class LegacyItem {
@Input() name = '';
@Output() picked = new EventEmitter<string>();
}Parents bind to both styles in exactly the same way. The difference is inside the child. A decorator input is a plain property, so you need ngOnChanges or a setter to react to changes. A signal input works directly with computed() and effect(). Use the signal APIs in new code. The decorator APIs are still supported, so you do not have to migrate existing components immediately.
Common Errors
- "Can't bind to 'items' since it isn't a known property of 'app-todo-list'." You forgot to add the child to the parent's
imports, or the input name or alias is misspelled. - Rendering
[object Object]or a function's source text. You wrote{{ items }}instead of{{ items() }}in the child template. - "Property 'set' does not exist on type 'InputSignal'." You tried to write to an input. Emit an output instead, or switch to
model(). - The list does not update after
push(). The array reference did not change. Useupdate()with a new array. - Passing data through many levels. If you thread the same input through three or more components that don't use it, move that state into a shared service. The services chapter covers this.
Exercise
A child component declares rating = input.required<number>() and rated = output<number>(). A parent writes <app-stars rating="4" (rated)="score = $event" />. Identify the compile-time problem and give two different fixes.
Show answer
rating="4" passes the string "4", but the input expects a number, so template type checking fails. Fix 1: use property binding with an expression, [rating]="4". Fix 2: declare the input with a transform, rating = input.required<number, unknown>({ transform: numberAttribute }), so the static string is converted. The output binding is fine. $event is a number, assuming score is a number field on the parent.
Exercise
Convert the Stepper so the parent can reject values below 0. Should you keep model() or switch to input() and output()? Sketch the child's class.
Show answer
Switch to input() and output(), because the parent must decide whether a change is accepted, while model() writes to the parent's signal directly. Child: value = input(0); valueChange = output<number>(); with buttons calling valueChange.emit(value() - 1) and valueChange.emit(value() + 1). The parent binds [value]="qty()" (valueChange)="onChange($event)" and calls qty.set(n) only when n >= 0.