In the event binding lesson, the note box needed a method, updateNote($event), only to copy the typing into the class. The other direction wasn't automatic either: if code empties note, the box keeps showing the old text.
Two-way binding handles both directions at the same time. One property in the class is tied to one input box in the template. What you type in the box changes the property right away, and when code changes the property, the box changes right away too. Picture the order note at Jali's Pancake Stall written on a small whiteboard that can be read from both sides. The customer writes "spicy" on the front, and Jali reads it right away from the back. When Jali wipes it, the customer's side is clean too. There's only one board, like the property note: the customer's side is the input box, and Jali's side is the code in the class.
[(ngModel)]: the input box and the property become one
This Order component has a note box, a Clear button and a paragraph that shows the note:
import { Component } from '@angular/core'
import { FormsModule } from '@angular/forms'
@Component({
selector: 'app-order',
standalone: true,
imports: [FormsModule],
template: `
<input [(ngModel)]="note" placeholder="Note" />
<button (click)="note = ''">Clear</button>
<p>Note: {{ note }}</p>
`,
})
export class Order {
note = 'no spring onions'
}
The box, the property and the paragraph at each step:
| Event | In the box | note |
<p> |
|---|---|---|---|
| The page first shows | no spring onions | 'no spring onions' |
Note: no spring onions |
| The box's text replaced with "spicy" | spicy | 'spicy' |
Note: spicy |
| Click Clear | (empty) | '' |
Note: |
ngModelis a directive from@angular/formsthat connects an input box to a property.- The first direction: property to box. When the page opens, the box already holds
no spring onions. When the Clear button runsnote = '', the box empties too. - The second direction: box to property. Each time you type a letter, the box's text becomes the value of
noteright away, so<p>changes without any method. - On a checkbox,
[(ngModel)]="agreed"storestrueorfalse, not text.
The first exercise uses the same shape: <input [(ngModel)]="name" placeholder="Type a name..." /> and <p>Hello, {{ name }}!</p>. Typing Sinta makes the paragraph read Hello, Sinta!.
Banana in a box: [( )] = [ ] + ( )
Square brackets outside, round brackets inside: the curved round brackets are the banana, and the square brackets are the box. That's why the form [()] is called banana in a box. It's only shorthand for two bindings you already know, property binding and event binding:
<input [(ngModel)]="note" />
<!-- exactly the same as: -->
<input [ngModel]="note" (ngModelChange)="note = $event" />
[ngModel]="note"(property binding) carries the value from the class to the box.(ngModelChange)="note = $event"(event binding) carries the box's new text back to the class.ngModelChangeis an event ofngModelthat happens every time the box's text changes. Here$eventholds the text in the box, not an event object.- If you write only
[ngModel], there's only one direction: the box is filled, but your typing never reachesnote. - The order of the brackets matters. Angular reads
([ngModel])as an event named[ngModel], and that event never happens. So the box is empty,notenever changes, and no error tells you.
FormsModule: without it, ngModel is unknown
ngModel isn't built into the template like @if. ngModel is a directive inside FormsModule (a set of directives for forms). So a standalone component has to import it in two places: import { FormsModule } from '@angular/forms' at the top of the file, and imports: [FormsModule] in @Component.
If you forget to import FormsModule, Angular doesn't recognise ngModel. The box becomes a plain HTML input that's empty when the page opens, even though note holds no spring onions. You can still type in it, but <p> stays at Note: no spring onions, because nothing carries your typing to the class. The console writes:
NG0303: Can't bind to 'ngModel' since it isn't a known property of 'input' (used in the 'Order' component template).
Two-way for your own component: [(count)]
Banana in a box also works on components you write yourself, as long as the pair is right: one @Input() named x, and one @Output() named exactly xChange. For example, this count picker with a - button and a + button:
@Component({
selector: 'app-count-picker',
standalone: true,
template: `
<button (click)="change(-1)">-</button>
<span>{{ count }}</span>
<button (click)="change(1)">+</button>
`,
})
export class CountPicker {
@Input() count = 1
@Output() countChange = new EventEmitter<number>()
change(step: number) {
const next = this.count + step
if (next < 1) {
return
}
this.count = next
this.countChange.emit(next)
}
}
The - and + buttons call change(). That method stops if the result is below 1. Otherwise it stores the new value and emits it through countChange. Its parent is the Order component:
<!-- Order's template, with CountPicker in imports and count = 1 -->
<app-count-picker [(count)]="count" />
<p>Total: {{ '$' + count * 10 }}</p>
[(count)]="count"is shorthand for[count]="count" (countChange)="count = $event".- Press + twice: the picker's number becomes 3, Order's
countbecomes 3 too, and the total readsTotal: $30. - If you name the output
countChanged, or forget to callemit, only the picker's number goes up: Order'scountstays at1, the total stays$10, and there's no error.
💡 model(): an input and output pair in one line
Since Angular 17.2, one line, count = model(1), can replace the @Input() and @Output() countChange pair. Its value is read as count() and changed with this.count.set(next). The parent still writes [(count)]="count". Like input() in the previous lesson, model() needs the Angular CLI. The exercise editor and the Playground don't recognise it (NG0303: Can't bind to 'count' since it isn't a known property of 'app-count-picker'), so here we use the decorator pair.
⚠️ The box sits still and the typing goes nowhere
- Forgetting
FormsModule. The box is empty, typing never reaches the class, and the console writes NG0303 forngModel. - Brackets the wrong way round.
([ngModel])does nothing, and there's no error. Remember the banana inside the box:[(...)]. - An output not named
xChange.[(count)]only works with an output namedcountChange. ngModelinside a<form>with noname. Angular refuses:If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone' in ngModelOptions.Addname="note", or don't wrap the box in a<form>.- Paragraph order in the second exercise. The grader reads the first
<p>, so<p>Email: {{ email }}</p>has to come before<p>Agreed: {{ agreed }}</p>. The Email paragraph also has to reademaildirectly, not copied once into another property.
TL;DR: Two-way binding ties one input box and one property in both directions: the class's value fills the box, and typing in the box changes the property. The form is [(ngModel)]="note", with ngModel, a directive from @angular/forms. The form [()] is called banana in a box (round brackets, the banana, inside square brackets, the box), and it's only shorthand for [ngModel]="note" (ngModelChange)="note = $event": property binding plus event binding. ngModel lives in FormsModule, so a standalone component needs imports: [FormsModule]. Without it the box is empty, typing doesn't reach the class, and the console writes NG0303. Your own component can be used with [(count)] when it has @Input() count and an @Output() countChange that it emits (sends to the parent) every time the value changes. model() is the short form of that pair in Angular CLI projects.
⚡ [(ngModel)] binds both ways
Write:
imports: [FormsModule],
template: `
<input [(ngModel)]="note" placeholder="Note" />
<p>Note: {{ note }}</p>
`,
Guess first: ngModel is a directive from FormsModule. If FormsModule is taken out of imports, does the box still show what's in note?
No. The box becomes a plain, empty HTML input, your typing never reaches the class, and the console writes NG0303 for ngModel.
Meaning: [(ngModel)] is two-way binding (binding in both directions) between the input box and the property note. The value of note in the class fills the box, and each time you type, the box's text becomes the value of note right away, so <p> changes too. In the exercise the box is tied to name: typing Sinta makes the <p> read Hello, Sinta!.
⚡ Banana in a box is shorthand
Write:
<input [(ngModel)]="note" />
<!-- exactly the same as: -->
<input [ngModel]="note" (ngModelChange)="note = $event" />
Meaning: The form [()] is called banana in a box: round brackets (the banana) inside square brackets (the box). It's shorthand for two bindings: [ngModel] carries the value from the class to the box, and (ngModelChange) carries the typing back to the class. The order of the brackets matters: ([ngModel]) does nothing, and there's no error. Remember, the banana goes inside the box: [(...)].
⚡ Two-way for your own component
Write:
@Input() count = 1
@Output() countChange = new EventEmitter<number>()
Meaning: The pair of the input count and the output countChange lets this count picker (with a - and a + button) be used with banana in a box. The parent writes [(count)]="count", as long as the output is named exactly countChange and is emitted every time the value changes. With another name, only the number in the picker changes, and the parent's count stays the same.