Angular - 2.16 bidirectional data link

Two-way data binding in Angular combines the two directions of data flow we have studied separately - property binding and event binding - into a single, compact expression. The dedicated directive is ngModel and it uses what Angular developers nickname the "banana-in-a-box" syntax: [(ngModel)]. The square brackets express the property binding, and the parentheses express the event binding.

Before you can use the directive, you must import FormsModule in your AppModule and add it to the imports array. Without that, Angular throws an error explaining that ngModel is unknown. Once the module is registered, you can write <input type="text" [(ngModel)]="serverName"> and Angular will keep the field and the class property in sync.

Two directions, one expression

  • The input is pre-filled with the initial value of serverName.
  • Every keystroke updates the class property; no manual (input) handler is required.
  • Changing serverName programmatically (from a button, a timer or an HTTP response) updates the input on screen.

To visualise the synchronisation, display the value next to the input: <p>Server name: {{ serverName }}</p>. As you type, the paragraph updates instantly. If you assign this.serverName = 'test server' in the class, the input shows that value the next time the change detection runs.

Two-way binding is the right tool for simple forms where you just need to read and write a single value. For more complex use cases - validation rules, custom controls, programmatic form construction - Angular offers Reactive Forms, a topic we will explore later. But [(ngModel)] remains the fastest way to wire a TypeScript field to a form control with a minimum of code.