Sub topic 10
Two-way binding with model()
This chapter assumes you know TypeScript classes and generics, standalone components, property binding [prop] and event binding (event), and how to read a signal by calling it. You should also have seen input() and output() from earlier chapters. Here you will learn how model() combines the two, and when to use it.
The problem model() solves
A form-like component such as a toggle, a rating picker, or a slider needs two things. It must show a value that the parent owns, and it must change that value when the user interacts with it.
With the tools you already have, that takes an input and an output with matching names:
import { Component, input, output } from '@angular/core';
@Component({
selector: 'app-toggle-manual',
template: `<button (click)="toggle()">{{ checked() ? 'On' : 'Off' }}</button>`,
})
export class ToggleManual {
checked = input(false);
checkedChange = output<boolean>();
toggle() {
this.checkedChange.emit(!this.checked());
}
}This works, but the child cannot write to checked, because inputs are read-only. It has to emit an event and wait for the parent to send a new value back. model() removes that boilerplate.
Declaring a model
model() creates a writable signal that is also an input and an output. Here is the toggle from the plan:
import { Component, model } from '@angular/core';
@Component({
selector: 'app-toggle',
template: `
<button (click)="toggle()">{{ checked() ? 'On' : 'Off' }}</button>
`,
})
export class Toggle {
checked = model(false);
toggle() {
this.checked.update((value) => !value);
}
}The single line checked = model(false) declares three things:
- An input named
checked, with the default valuefalse. - An output named
checkedChange. Angular builds the name by appendingChangeto the property name. - A writable signal. You read it by calling
checked(), and you write it withset()andupdate().
The output name is the reason two-way binding works. The [(checked)] syntax expects an input checked and an output checkedChange.
Binding a model in the parent
The parent uses the "banana in a box" syntax, [(prop)]:
<app-toggle [(checked)]="isOn" />Here is a complete parent component. The bound expression must be writable, so a signal() or a plain property both work:
import { Component, signal } from '@angular/core';
import { Toggle } from './toggle';
@Component({
selector: 'app-settings',
imports: [Toggle],
template: `
<app-toggle [(checked)]="darkMode" />
<p>Dark mode is {{ darkMode() ? 'on' : 'off' }}</p>
`,
})
export class Settings {
darkMode = signal(false);
}When the user clicks the button, the child updates its model. Angular emits checkedChange and writes the new value into darkMode. The paragraph in the parent updates because it reads that signal.
What the syntax expands to
[(checked)]="darkMode" is shorthand for a property binding plus an event binding. For a signal in the parent, it is equivalent to:
<app-toggle [checked]="darkMode()" (checkedChange)="darkMode.set($event)" />If you bind a plain property, the event half assigns the property instead. If you write the two halves yourself, you can add logic between them, such as validation or logging, which the shorthand cannot do.
How writes behave
A model is a signal, so it follows signal rules.
- Calling
set()orupdate()in the child changes the local value immediately. The child sees the new value on its next read. - The output emits only when the value actually changes. Setting a model to the value it already holds does not emit
checkedChange. - Values coming from the parent through the binding do not emit the output. Only writes made inside the child do. This prevents a loop where the parent's new value bounces straight back.
The last rule matters when the parent and child disagree. If the child calls set(true) and the parent ignores the event, the child keeps showing true until the parent next pushes a value in. The child's model is a local copy that the parent can overwrite.
Required models
Use model.required<T>() when the parent must always supply a value. A rating component is a good example:
import { Component, computed, model } from '@angular/core';
@Component({
selector: 'app-rating',
template: `
@for (star of stars(); track star) {
<button (click)="rating.set(star)">
{{ star <= rating() ? '★' : '☆' }}
</button>
}
`,
})
export class Rating {
rating = model.required<number>();
stars = computed(() => [1, 2, 3, 4, 5]);
}The parent must now bind rating, with either [(rating)] or [rating]. Otherwise the compiler reports an error. As with input.required(), reading a required model before the parent sets it throws at runtime. In practice, that means you should not read it in the constructor or in a field initializer.
Using a model without two-way syntax
A model is still an ordinary input and output, so a parent can use just one half.
<app-toggle [checked]="true" />
<app-toggle (checkedChange)="log($event)" />The first form passes a value in and ignores changes. The second form listens for changes and leaves the default false as the starting value. This is useful when the parent only wants to observe.
Aliasing a model
model() accepts an alias option, as input() does. The alias renames the input. The output name follows it, with Change appended:
import { Component, model } from '@angular/core';
@Component({
selector: 'app-volume',
template: `<input type="range" min="0" max="100"
[value]="level()"
(input)="level.set(+$any($event.target).value)" />`,
})
export class Volume {
level = model(50, { alias: 'volume' });
}A parent would write <app-volume [(volume)]="vol" />, and the output is volumeChange. Use aliases sparingly, because they hide the real property name from readers of the child class.
model() does not support the transform option. The value written by the child and the value received from the parent must have the same type, so there is no place to convert an attribute string. If you need coercion, accept the raw value in a separate input() with a transform, or normalize it in a computed().
Deriving state from a model
You can read a model inside computed() and effect(), just like an input:
import { Component, computed, model } from '@angular/core';
@Component({
selector: 'app-quantity',
template: `
<button (click)="quantity.update((q) => q - 1)" [disabled]="atMinimum()">-</button>
<span>{{ quantity() }}</span>
<button (click)="quantity.update((q) => q + 1)">+</button>
`,
})
export class Quantity {
quantity = model(1);
atMinimum = computed(() => this.quantity() <= 1);
}Whether the value came from the parent or from a click in the child, atMinimum stays correct. This is the main advantage of a model over a hand-written input and output pair. The component has one source of truth to read from.
model() or input() plus output()?
| Situation | Use |
|---|---|
| The child only displays the value | `input()` |
| The child reports events that are not "the new value" (a click, a submit) | `output()` |
| The child edits a value the parent owns, and the two should stay in sync | `model()` |
| The parent must transform or validate each change before accepting it | `input()` plus `output()`, bound by hand |
Most components need only a few models, usually form-like controls. Prefer input() and output() when the data flow is one-directional, because the flow is easier to trace.
Common mistakes
- Binding a non-writable expression.
[(checked)]="isOn()"fails because a call result cannot be assigned to. Bind the signal itself, as in[(checked)]="isOn". - Binding a read-only signal. A
computed()signal cannot be the target of a two-way binding because it has noset(). Use asignal(). - Expecting the output to fire on parent writes. It fires only for writes made in the child.
- Mutating objects in place. If the model holds an object or array, call
set()with a new object. Mutating the existing one gives signals nothing to compare, so the change is not detected. - Overusing models. If every property is a model, ownership of state becomes unclear. Decide which component owns each value.
Exercise
A child declares count = model(0). What are the names of the input and output it exposes, and what does <app-child [(count)]="total" /> expand to when total is a signal in the parent?
Show answer
The input is count and the output is countChange. The binding expands to <app-child [count]="total()" (countChange)="total.set($event)" />.
Exercise
A child calls this.checked.set(true) on a model that is already true. Does checkedChange emit? What happens when the parent changes its own bound value from true to false?
Show answer
No, it does not emit, because the value did not change. When the parent changes the value, the child's model becomes false, and checkedChange does not emit, because only writes made inside the child trigger the output.
Exercise
Why does <app-toggle [(checked)]="isOn()" /> fail to compile, and how do you fix it?
Show answer
A two-way binding must assign the emitted value back to its target, and a function call such as isOn() cannot be assigned to. Bind the writable signal itself: <app-toggle [(checked)]="isOn" />.