Angular - 2.16 bidirectional data link
In the previous lessons we covered property binding and event binding separately. Two-way data binding combines both into a single expression so that the template and the component class stay synchronised in real time. Angular ships a dedicated directive for that purpose: ngModel, used through the so-called "banana-in-a-box" syntax [(ngModel)].
To use ngModel you must first import FormsModule in your AppModule and add it to the imports array. Without that step Angular will report that ngModel is not a known property of input. Once the module is wired up, the template syntax looks like this: <input type="text" [(ngModel)]="serverName">. The square brackets handle the property binding (push value from class to input) while the parentheses handle the event binding (push value from input back to the class).
What two-way binding gives you
- The input field is automatically pre-filled with the current value of
serverName. - Typing in the field updates
serverNameon every keystroke - no manual(input)handler required. - Changing
serverNameprogrammatically (e.g. through a button or a timer) updates the input on screen.
You can demonstrate the bidirectional behaviour by displaying the value next to the input with interpolation: <p>Server name: {{ serverName }}</p>. As you type, the paragraph updates in real time, proving that the component property reflects every change. Conversely, if you initialise serverName = 'test server' in the class, the input shows that value as soon as the page loads.
Two-way binding is the cleanest pattern for simple forms: a single line of HTML covers both directions. For more complex form scenarios - validation, custom controls, conditional logic - Angular also offers Reactive Forms, which we will introduce later in the course. But for everyday inputs, [(ngModel)] remains the go-to tool to keep a TypeScript field and an HTML control perfectly in sync.