Angular - 2.18 Bidirectional data link

In the previous lessons we learned a lot about event binding and property binding. Now we are going to fuse the two and obtain a two-way connection. We already know that we can retrieve data emitted by an event with the $event object and a method handler, but there is an even simpler approach when both directions of the flow are needed at the same time.

Two-way binding merges the property-binding brackets and the event-binding parentheses into a single combined syntax: [(ngModel)]. The directive is named ngModel and we will dig into it more later. The expression assigned between the quotes is a property of the TypeScript class - for example serverName. The full binding is therefore <input type="text" [(ngModel)]="serverName">.

What this setup does

  • It listens to the native input event and automatically updates serverName in the component as soon as the user types.
  • It also pushes the current value of serverName back to the input field whenever the property changes from elsewhere in the code.

To prove the two directions, initialise serverName = 'test server' in the class. When the application loads, the input is pre-filled with that value. If, for demonstration, you keep the previous input that used only one-way event binding next to the new one, you can see that this old input stays empty. As soon as you type in the [(ngModel)] input, the interpolation that displays the value and the property itself both update on every keystroke. Typing in the old one-way input changes nothing in the two-way input, exactly because it does not have the bidirectional link.

Two-way binding is therefore a very compact and effective way to react to user input in both directions. It is built on top of the property and event bindings we already know, but it removes all the boilerplate. From here we will polish the application a little and move on to another essential Angular feature: directives.