Sub topic 12
Building Components That Support Two-Way Binding
You have already used [(ngModel)] on form controls and seen model() in passing. This chapter shows how to make your own components accept the banana-in-a-box syntax, [(value)]="field". It covers the decorator-based convention, the model() API, and the mistakes that cause silent desync or change-detection errors.
It assumes you know property and event binding, @Input/@Output, and the basics of signals and input()/output(), all covered in earlier chapters.
What the Compiler Does with `[(x)]`
Two-way binding on a component is not a separate feature. The Angular compiler rewrites it into one property binding and one event binding that follow a naming rule:
| You write | Angular compiles it to |
|---|---|
| `[(value)]="score"` | `[value]="score" (valueChange)="score = $event"` |
| `[(value)]="scoreSignal"` (a `WritableSignal`) | `[value]="scoreSignal()" (valueChange)="scoreSignal.set($event)"` |
So a component supports [(value)] when it has an input named value and an output named valueChange. The output name must be the input name with Change added. Angular does not check that the two belong together. It only looks for those two names.
The Decorator-Based Pattern
This star rating component follows the convention with @Input and @Output:
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-rating',
template: `
@for (star of stars; track star) {
<button type="button" [class.on]="star <= value" (click)="select(star)">★</button>
}
`,
styles: [`.on { color: gold; }`],
})
export class RatingComponent {
stars = [1, 2, 3, 4, 5];
@Input() value = 0;
@Output() valueChange = new EventEmitter<number>();
select(star: number) {
this.value = star;
this.valueChange.emit(star);
}
}
@Component({
selector: 'app-root',
imports: [RatingComponent],
template: `
<app-rating [(value)]="score" />
<p>Score: {{ score }}</p>
`,
})
export class AppComponent {
score = 3;
}select() does two separate things:
- It updates
this.valueso the child renders the new state right away, even if the parent only uses one-way[value]and ignores the event. - It emits the new value so a parent using two-way binding can store it.
If you leave out step 1, a parent that binds only [value] sees a rating that never changes. If you leave out step 2, [(value)] works the same as [value] and the parent's score stays at 3.
The `model()` Pattern
model() declares a writable signal that is also an input. Angular creates the matching Change output for you, so the naming rule cannot drift out of sync.
import { Component, model, signal } from '@angular/core';
@Component({
selector: 'app-toggle',
template: `
<button type="button" role="switch"
[attr.aria-checked]="checked()"
(click)="toggle()">
{{ checked() ? 'On' : 'Off' }}
</button>
`,
})
export class ToggleComponent {
checked = model(false);
toggle() {
this.checked.update(v => !v);
}
}
@Component({
selector: 'app-root',
imports: [ToggleComponent],
template: `
<app-toggle [(checked)]="darkMode" />
<app-toggle [(checked)]="notifications" />
<p>Dark mode: {{ darkMode() }}, notifications: {{ notifications }}</p>
`,
})
export class AppComponent {
darkMode = signal(true);
notifications = false;
}Calling set() or update() on a model does what the decorator version needed two lines for: the local value changes and checkedChange fires. The parent can bind either a WritableSignal (darkMode) or a plain field (notifications). The compiler picks .set($event) or plain assignment depending on the type.
Because the output really exists, the parent can also use just one side of it:
<app-toggle [checked]="true" (checkedChange)="log($event)" />Required models and aliases
model.required<T>() makes the parent supply a value, just like input.required(). An alias renames both sides:
import { Component, model } from '@angular/core';
@Component({
selector: 'app-slider',
template: `
<input type="range" min="0" max="100"
[value]="level()"
(input)="level.set(+$any($event.target).value)">
`,
})
export class SliderComponent {
level = model.required<number>({ alias: 'value' });
}Parents write [(value)]="volume", and the generated output is valueChange. Inside the class you still use level.
Choosing Between the Two
| Concern | `@Input` + `@Output` | `model()` |
|---|---|---|
| Naming of the `Change` output | Manual, easy to mistype | Generated |
| Local update and emit | Two statements | One `set()`/`update()` |
| Reading in `computed()`/`effect()` | Not reactive | Reactive signal |
| `transform` option (e.g. `booleanAttribute`) | Supported on `@Input` | Not supported |
| Works with older code using `ngOnChanges` | Yes | Changes do not show up as a plain field |
New components should use model(). Keep the decorator pattern when you need an input transform, or when the rest of the component is decorator-based and you don't want to mix styles.
Gotchas and Failure Modes
Emitting when the parent changes the input
Emit only in response to something that happens inside the child, such as a click or a keystroke. If you emit when a new input value arrives, for example in ngOnChanges or in an effect() that watches the model, the parent reassigns the same value. In development mode that can raise ExpressionChangedAfterItHasBeenCheckedError, and with objects it can loop forever. model() already follows this rule: a new value from the parent updates the signal but does not fire checkedChange.
Binding a signal's value instead of the signal
<!-- Wrong: darkMode() is a boolean, not an assignable target -->
<app-toggle [(checked)]="darkMode()" />
<!-- Right -->
<app-toggle [(checked)]="darkMode" />The first form fails to compile because the event half would try to assign to a function call. The same rule rules out literals and expressions such as [(value)]="score + 1". The right side of [(x)] must be something you can assign to, or a writable signal.
Mismatched names
With decorators, @Output() changed or @Output() valueChanged breaks the binding silently. The compiler still accepts [(value)]. It just listens for an event your component never emits, which you will only see as a parent field that never updates. Under strict template checking you get a compile error for the unknown output, so keep strictTemplates turned on.
Mutating objects in place
If the bound value is an object or array, changing it in place (this.items().push(x)) does not emit anything. It also breaks OnPush parents and signal equality checks. Emit a new reference instead:
this.items.update(list => [...list, x]);Validating or clamping values
When the child rejects or adjusts what the user entered, emit the corrected value, not the raw one. For example, this.level.set(Math.min(100, Math.max(0, raw))). Then the parent and child agree. If the parent sends an out-of-range value, decide whether the child clamps it only for display or writes the corrected value back. Writing it back is the "emit on input change" mistake above, so prefer clamping for display, for example with a computed().
Custom Two-Way Binding Versus ngModel
[(value)] on your component is not the same as making it work with [(ngModel)] or with reactive forms. To work with forms, a component must implement ControlValueAccessor and register itself with NG_VALUE_ACCESSOR. That gives you touched/dirty state, validators, and formControlName. Use model() for widgets that only need parent-child sync. Implement ControlValueAccessor when the component is a form field that should take part in validation.
Exercise
A teammate writes @Input() open = false; and @Output() openChanged = new EventEmitter<boolean>(); on a dialog component. The parent uses <app-dialog [(open)]="isOpen" />. Closing the dialog from inside never resets isOpen. Why, and what are two ways to fix it?
Show answer
[(open)] compiles to (openChange)="isOpen = $event", but the component emits openChanged, so the parent listens for an event that never fires. Fix it by renaming the output to openChange, or by replacing both members with open = model(false) and calling this.open.set(false) when the dialog closes.
Exercise
Write a QuantityComponent with selector app-quantity that supports [(qty)], shows minus and plus buttons, and never lets the value go below 0. Use model().
Show answer
import { Component, model } from '@angular/core'; @Component({ selector: 'app-quantity', template: '<button type="button" (click)="change(-1)">-</button> {{ qty() }} <button type="button" (click)="change(1)">+</button>' }) export class QuantityComponent { qty = model(0); change(delta: number) { this.qty.update(q => Math.max(0, q + delta)); } }. The update() call both re-renders the child and emits qtyChange with the clamped value.
Exercise
Why should a child component not call this.value.set(...) inside an effect() that reads the value model to normalize what the parent passed in?
Show answer
The write emits valueChange in response to the parent's input, not to user action. The parent reassigns the value, which can trigger the effect again. That risks loops and ExpressionChangedAfterItHasBeenCheckedError. Normalize for display with a computed() instead, and emit only from user-driven handlers.