Sub topic 7
Two-Way Binding and the Banana-in-a-Box Syntax
This chapter assumes you already know property binding ([prop]="expr") and event binding ((event)="handler($event)") from the earlier chapters. You should also be comfortable reading a component class written in TypeScript. Two-way binding is built entirely from those two forms. Once you see how Angular expands it, most of the errors people hit with it stop being surprising.
One-Way Flow in Both Directions
Every binding covered so far moves data in one direction:
| Syntax | Direction | Example |
|---|---|---|
| `{{ expr }}` | Component to view | `{{ name }}` |
| `[target]="expr"` | Component to view | `[disabled]="!canEdit"` |
| `(event)="statement"` | View to component | `(click)="save()"` |
| `[(target)]="field"` | Both directions | `[(size)]="fontSize"` |
Two-way binding is a property binding and an event binding written on the same target, plus a naming rule that connects them. It is not a separate kind of data flow. The [( )] notation is often called "banana in a box": the parentheses are the banana and the square brackets are the box around it. A quick way to remember the order is that the box goes on the outside.
What the Compiler Does with `[( )]`
When Angular compiles a template and finds [(x)]="y", it rewrites it into two bindings:
[(x)]="y"
becomes
[x]="y" (xChange)="y = $event"These rules come out of that expansion:
- The target must have an input named
x. - The target must emit an event named exactly
xChange. Angular adds theChangesuffix itself, so the name has to match. - The right-hand side must be something you can assign to, because Angular generates
y = $event.
Here is a complete example that puts the shorthand and the expanded form side by side. The child is a minimal font sizer. Building components like this is covered in detail later in the tutorial, so here it only provides a target to bind to.
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-sizer',
template: `
<button (click)="change(-1)" aria-label="Smaller">-</button>
<button (click)="change(1)" aria-label="Bigger">+</button>
<span [style.font-size.px]="size">{{ size }}px</span>
`,
})
export class SizerComponent {
@Input() size = 16;
@Output() sizeChange = new EventEmitter<number>();
change(delta: number) {
this.size = Math.min(40, Math.max(8, this.size + delta));
this.sizeChange.emit(this.size);
}
}
@Component({
selector: 'app-root',
imports: [SizerComponent],
template: `
<h3>Shorthand</h3>
<app-sizer [(size)]="fontSize" />
<h3>Expanded (equivalent)</h3>
<app-sizer [size]="fontSize" (sizeChange)="fontSize = $event" />
<p [style.font-size.px]="fontSize">Parent text at {{ fontSize }}px</p>
`,
})
export class AppComponent {
fontSize = 16;
}Click either sizer and both stay in step with the parent paragraph. Here is the sequence: the child changes its own size and emits sizeChange. The parent's generated handler assigns the new value to fontSize. Change detection then pushes fontSize back down to both sizers through their [size] bindings.
Choosing Between Shorthand and Expanded Form
The shorthand is fine when the parent only needs to store whatever the child reports. Switch to the expanded form when any of these apply:
- You need to validate, clamp or round the value before storing it.
- The value is stored somewhere that isn't a plain assignable field, such as a service method call or a store action.
- You want a side effect on every change, such as logging or saving a draft.
- You want to bind the input one way and handle the event in some other way.
import { Component } from '@angular/core';
import { SizerComponent } from './sizer.component';
@Component({
selector: 'app-settings',
imports: [SizerComponent],
template: `
<app-sizer [size]="fontSize" (sizeChange)="onSize($event)" />
<p>Saved size: {{ fontSize }}</p>
`,
})
export class SettingsComponent {
fontSize = 16;
onSize(next: number) {
// Only accept even sizes, and persist each accepted change.
if (next % 2 === 0) {
this.fontSize = next;
localStorage.setItem('fontSize', String(next));
}
}
}This example has a catch. When the parent rejects an odd value, the child has already set its own size to that odd number. The parent's fontSize did not change, so Angular has no new input value to push down, and the child shows a number the parent never accepted. Controlled components are one way to avoid this: the child emits a proposal without updating its own state and waits for the input to come back. That design is covered in the chapter on building components that support two-way binding.
What Can Go on the Right-Hand Side
Because the compiler generates an assignment, the right-hand side has to be an assignable expression, sometimes called an lvalue. Angular also accepts a writable signal and generates .set($event) for it instead of an assignment.
| Right-hand side | Allowed | Reason | Column |
|---|---|---|---|
| `fontSize` | Yes | A plain field can be assigned | |
| `settings.fontSize` | Yes | A property access can be assigned | |
| `sizes[i]` | Yes | A keyed access can be assigned | |
| `fontSize` where `fontSize = signal(16)` | Yes | Angular calls `fontSize.set($event)` | |
| `fontSize()` | No | A function call result can't be assigned | |
| `settings?.fontSize` | No | Safe navigation can't be assigned | |
| `fontSize + 1` | No | An arithmetic result can't be assigned | |
| `fontSize \ | number` | No | Pipes aren't allowed in two-way bindings |
The signal row matters more and more as code moves to signals. Write the signal itself, not a call to it:
import { Component, signal } from '@angular/core';
import { SizerComponent } from './sizer.component';
@Component({
selector: 'app-signal-host',
imports: [SizerComponent],
template: `
<app-sizer [(size)]="fontSize" />
<p>Signal value: {{ fontSize() }}</p>
`,
})
export class SignalHostComponent {
fontSize = signal(16);
}Inside [( )], Angular reads the signal for the input side and calls set for the output side. Writing [(size)]="fontSize()" fails to compile because the result of a call can't be assigned. Binding a writable signal this way needs Angular 17.2 or later.
Common Errors and Their Causes
Swapped brackets
([size])="fontSize" is not two-way binding. Angular reads it as an event binding to an event literally named [size], which never fires. The box goes outside: [(size)].
Misnamed output
If the child declares @Output() sizeChanged or @Output() onSizeChange, then [(size)] compiles to a listener for sizeChange, which doesn't exist. With strictTemplates turned on, the compiler reports an unknown event on a component. Without it, the value flows down and changes never come back up. The output name must be the input name plus Change, with the same capitalization.
`[(value)]` on a native element
Writing <input [(value)]="name"> looks reasonable, but native elements don't emit a valueChange event. The expansion produces a working [value] binding and a listener for a DOM event nobody dispatches, so you get one-way binding with no error. This gap is why form controls need a directive such as ngModel, which the next chapter covers. If you don't want the forms module, write the two halves yourself:
import { Component } from '@angular/core';
@Component({
selector: 'app-native',
template: `
<input [value]="name" (input)="name = $any($event.target).value">
<p>Name: {{ name }}</p>
`,
})
export class NativeComponent {
name = 'Ada';
}Emitting during input processing
If the child emits sizeChange while it receives an input, for example in a setter or in ngOnChanges, the parent's value changes in the middle of a change detection pass. In development mode this usually raises ExpressionChangedAfterItHasBeenCheckedError. Emit only in response to something new happening, such as a user action or an async result. Don't emit to echo a value that just arrived.
Expecting deep updates to flow back
Two-way binding reports a value only when the child emits. If the child mutates a field of an object it received, for example this.user.name = 'x', the parent sees the change because both hold the same reference. But no event fires, so any parent logic in the change handler never runs. Emit a new object instead of mutating the shared one, so that every change goes through the event.
When Not to Use Two-Way Binding
Two-way binding suits values that behave like a control's current value: a text field's contents, a toggle's state, a slider position, a selected tab. It suits commands or one-off notifications poorly. Use a normal output with a verb-style name for those, such as (save), (remove) or (reset). A useful test is whether the parent would reasonably store the emitted value in the same field it passes down. If not, it is an event, not two-way state.
Exercise
A teammate writes <app-rating [(stars)]="review?.stars" /> and the build fails. The RatingComponent has @Input() stars = 0 and @Output() starsChange = new EventEmitter<number>(). Explain why it fails and give two fixes.
Show answer
[(stars)] expands to [stars]="review?.stars" (starsChange)="review?.stars = $event", and Angular can't assign to a safe-navigation expression. Fix 1: make sure review always exists (for example, initialize it or wrap the element in an @if (review) block) and bind [(stars)]="review.stars". Fix 2: use the expanded form, [stars]="review?.stars ?? 0" (starsChange)="setStars($event)", with a method that handles a missing review.
Exercise
You write <input [(value)]="query"> and the paragraph showing {{ query }} never updates when you type, but there is no error. Why, and what is the smallest fix that doesn't import FormsModule?
Show answer
The shorthand expands to [value]="query" (valueChange)="query = $event". A native input never dispatches a valueChange event, so only the downward half works. Write both halves yourself: <input [value]="query" (input)="query = $any($event.target).value">.
Exercise
Rewrite <app-sizer [(size)]="fontSize" /> in expanded form so that the parent logs every change to the console and stores the value. Assume fontSize is a writable signal.
Show answer
<app-sizer [size]="fontSize()" (sizeChange)="fontSize.set($event); log($event)" />, with a component method log(v: number) { console.log('size', v); }. In the expanded form you have to call the signal on the input side and call set explicitly on the output side.