Sub topic 9
Parent-Child Data Flow with @Input and @Output
Components rarely work alone. A list component renders item components, and a form renders field components. The parent needs to hand data down, and the child needs to report what happened. Angular handles both directions with two decorators. @Input marks a property the parent can bind into. @Output marks an event the parent can listen to.
This chapter assumes you already know property binding ([prop]="expr") and event binding ((event)="handler($event)") from earlier chapters, and that you can create standalone components with the Angular CLI. Signal-based input(), output() and model() are covered in a later chapter. Here the focus is the decorator APIs, which you will find in most existing Angular code.
The Working Model: Data Down, Events Up
The rule is short. The parent owns the data and passes it down through inputs. The child never changes the parent's data directly. When the child wants a change, it emits an event, and the parent decides what to do with it.
When you use a child component, the syntax is the same as for native elements. [id]="7" is a property binding, but the target is the child's @Input property, not a DOM property. (remove)="onRemove($event)" is an event binding, but the source is the child's @Output emitter, not a DOM event.
A Complete Parent-Child Example
The child declares one input and one output. EventEmitter<number> types the payload, so the parent's $event is a number.
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-item',
template: `<button (click)="remove.emit(id)">Remove {{ id }}</button>`,
})
export class ItemComponent {
@Input() id = 0;
@Output() remove = new EventEmitter<number>();
}The parent imports the child, binds each id, and handles remove by replacing its array.
import { Component } from '@angular/core';
import { ItemComponent } from './item.component';
@Component({
selector: 'app-item-list',
imports: [ItemComponent],
template: `
@for (id of ids; track id) {
<app-item [id]="id" (remove)="onRemove($event)" />
}
<p>{{ ids.length }} items left</p>
`,
})
export class ItemListComponent {
ids = [3, 7, 9];
onRemove(id: number) {
this.ids = this.ids.filter(x => x !== id);
}
}The child does not know there is an array, and it does not delete anything. It only says "remove was requested for this id". That keeps ItemComponent reusable in any parent that wants to handle removal differently.
Configuring Inputs
@Input accepts an options object. It has three options you will use often.
Required inputs
@Input({ required: true }) makes the compiler report an error when a parent uses the component without binding that input. This check happens at build time. Pair it with a definite assignment assertion (!) because there is no sensible default.
Aliases
alias sets the public binding name separately from the class property name. It is useful when an existing template API must stay stable after a rename. Use it sparingly, because readers then have to map two names in their heads.
Transforms
transform converts the bound value before it is assigned. Angular ships booleanAttribute and numberAttribute for the most common case: static attributes in templates are always strings.
import { Component, Input, booleanAttribute, numberAttribute } from '@angular/core';
@Component({
selector: 'app-badge',
template: `
<span [class.muted]="disabled" [style.font-size.px]="size">{{ text }}</span>
`,
})
export class BadgeComponent {
@Input({ required: true }) text!: string;
@Input({ alias: 'badgeSize', transform: numberAttribute }) size = 12;
@Input({ transform: booleanAttribute }) disabled = false;
}A parent can now write <app-badge text="New" badgeSize="16" disabled />. Without the transforms, size would receive the string "16", and disabled would receive the empty string "", which is falsy. booleanAttribute treats the bare attribute's presence as true, matching how native disabled works.
Notice that text="New" with no brackets also works. A plain attribute on a component whose input has the same name sets the input to that static string. Use brackets when the value is an expression.
Reacting to Input Changes
An input is a plain property, so assigning to it does not run any code by default. Two techniques let the child react when the parent sends a new value.
ngOnChanges
ngOnChanges runs before ngOnInit and then again each time any input binding receives a new value. It receives a SimpleChanges map keyed by property name.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-user-card',
template: `<p>{{ status }}</p>`,
})
export class UserCardComponent implements OnChanges {
@Input({ required: true }) userId!: number;
status = '';
ngOnChanges(changes: SimpleChanges) {
const change = changes['userId'];
if (change) {
this.status = change.firstChange
? `Loaded user ${change.currentValue}`
: `Switched from ${change.previousValue} to ${change.currentValue}`;
}
}
}Input setters
A setter runs on every assignment to one input. It is handy when the logic concerns just that input.
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-title',
template: `<h3>{{ display }}</h3>`,
})
export class TitleComponent {
display = '';
@Input() set title(value: string) {
this.display = value.trim().toUpperCase();
}
}| Technique | Fires for | Sees previous value | Best for |
|---|---|---|---|
| `ngOnChanges` | Any input change, batched | Yes | Logic depending on several inputs together |
| Input setter | One input, each assignment | Only if you store it | Normalizing or deriving from one input |
| `transform` option | One input, each assignment | No | Pure type conversion |
Gotchas and Common Errors
Changes are detected by reference
Angular compares the old and new input values with ===. If the parent pushes into an array that it already passed down, the reference does not change. ngOnChanges does not fire, and a child using OnPush change detection does not re-render. That is why onRemove above uses filter, which returns a new array.
Mutating an input mutates the parent
Objects and arrays are passed by reference. If the child does this.user.name = 'x' on an input object, it edits the parent's object behind the parent's back. The "data down, events up" rule exists to stop this. Emit an event instead, or copy the value before editing it.
Output names that collide with DOM events
If you name an output click, a parent's (click) binding on your component listens to both the native DOM click bubbling from inside your template and your emitter. The handler can run twice with two different $event types. Pick names that describe intent: remove, selected, valueChange.
Outputs do not bubble
A DOM event bubbles up the element tree. A component output does not. Only the direct parent that bound (remove) hears it. To reach a grandparent, the middle component must re-emit, or the components should share a service.
The child must be imported
If the parent forgets imports: [ItemComponent], the compiler reports that app-item is not a known element. It also reports that it cannot bind to id because that is not a known property.
| Symptom | Likely cause | Fix |
|---|---|---|
| "Can't bind to 'id' since it isn't a known property" | Child not imported, or the property lacks `@Input` | Add to `imports`, add the decorator |
| Input is `undefined` in the constructor | Inputs are not bound yet | Move the logic to `ngOnInit` or `ngOnChanges` |
| Child doesn't update after `array.push` | Same reference | Pass a new array or object |
| `$event` typed as `any` or wrong | Untyped `EventEmitter` | Use `EventEmitter<T>` |
| `disabled` attribute acts as false | String `""` is falsy | Add `transform: booleanAttribute` |
When to Use This Pattern
Inputs and outputs fit direct parent-child relationships. Data passes one level, and the contract is visible in the template. Use a shared service or a state store when data must cross several levels, or when siblings need to talk without going through a common parent. Passing inputs down through three or more layers of components that don't use them is called prop drilling, and it is a signal to switch approaches.
A related pattern pairs an input value with an output valueChange, which lets a parent use [(value)]. A later chapter on custom two-way binding builds that pattern out.
Exercise
A parent holds tags = ['a', 'b'], binds <app-tag-list [tags]="tags" />, and later runs this.tags.push('c'). The child logs inside ngOnChanges, but nothing is logged after the push. Why, and what one-line change in the parent fixes it?
Show answer
Angular compares input values by reference, and push mutates the same array, so the binding sees no change and ngOnChanges does not run. Replace the push with this.tags = [...this.tags, 'c']; so that a new array reference is bound.
Exercise
Write a RatingComponent with a required numeric input stars that also accepts a static string such as stars="4", and an output rated that emits the clicked star number (1 to 5) as a number. Show how a parent would use it.
Show answer
Use @Input({ required: true, transform: numberAttribute }) stars!: number; and @Output() rated = new EventEmitter<number>();. In the template, loop with @for (n of [1, 2, 3, 4, 5]; track n) { <button (click)="rated.emit(n)">{{ n <= stars ? '★' : '☆' }}</button> }. The parent imports RatingComponent and writes <app-rating stars="4" (rated)="onRated($event)" />, where onRated(value: number) receives the star number.