Two-Way Binding
[(ngModel)] binds a form field both ways: the field shows the signal's value, and typing in the field changes the signal. Import FormsModule to use it. Brackets in and parentheses out, together: the banana in a box.
Apprentice · Angular · Updated
After this lesson you can
- Keep a form field and a signal in step with [(ngModel)] and FormsModule
Key takeaways
[(ngModel)]="name"keeps a form field and a signal in step: the field shows the signal's value, and typing changes it.- Give
[(ngModel)]the signal itself,name, without parentheses, and addFormsModuleto the component'simports. - The banana in a box is written
[()], brackets outside and parentheses inside, never([]). [(ngModel)]works with every kind of field: a checkbox givestrueorfalse, and a list gives the chosen option'svalue.
Forms need data to flow both ways: the field shows the current value, and typing changes it. You could write both halves, [value] in and (input) out. Angular has a shortcut: two-way binding.
[(ngModel)]
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
imports: [FormsModule],
selector: 'app-greeting',
template: `
<label class="form-label" for="name">Your name</label>
<input class="form-control" id="name" [(ngModel)]="name">
<p class="mt-2">Hello, {{ name() }}!</p>
<button class="btn btn-link" (click)="name.set('')">Clear</button>
`,
})
export class Greeting {
protected readonly name = signal('Ada');
}
- The field starts showing Ada, the signal's value.
- Type Grace, and the paragraph says Hello, Grace! as you type: the field changes the signal.
- Click Clear, and the field empties: the signal changes the field.
ngModel comes from FormsModule, so the component imports it. And [(ngModel)]="name" is given the signal itself, name, without parentheses: Angular reads it and sets it for you.
Banana in a box
[( )] is brackets and parentheses: data in and events out. Angular developers call it the banana in a box: the parentheses are the bananas, inside the brackets. (Write it [()], never ([]).)
Checkboxes and lists
[(ngModel)] works with every kind of form field:
<input type="checkbox" class="form-check-input" [(ngModel)]="giftWrap">
<select class="form-select" [(ngModel)]="shipping">
<option value="standard">Standard</option>
<option value="express">Express</option>
</select>
<p>{{ giftWrap() ? 'Gift wrapped' : 'No gift wrap' }}, {{ shipping() }} shipping</p>
With giftWrap = signal(false) and shipping = signal('standard'), a checkbox gives true/false, and a list gives the chosen option's value.
Check yourself
1 question to try on the lesson page.
So what
[(ngModel)] ties a form field to a signal both ways: one binding instead of two, and the field and your data can never disagree.