What is Data Binding?
Data binding is a core feature of Angular that coordinates the communication between a component's TypeScript class (the logic) and its HTML template (the view). As a Technical Lead, you know that efficient data flow is the backbone of a responsive UI. Angular provides four distinct types of binding, categorized by the direction of data flow.
- From Source to View (One-Way)
This type of binding pushes data from the TypeScript class into the HTML template. It is used to display dynamic content or set element properties.
- Interpolation
{{ value }}: Used to render text content within HTML tags. - Property Binding
[property]="value": Used to set the property of an element or a directive (e.g., [disabled], [src], [hidden]).
- From View to Source (One-Way)
This binding handles user interactions, such as clicks, keystrokes, and mouse movements, by calling methods in your TypeScript class.
- Event Binding
(event)="method()": Listens for specific DOM events and triggers logic in the component.
- Two-Way Binding
Two-way binding allows for a continuous synchronization of data between the view and the source. If the user changes a value in an input field, the TypeScript variable updates; if the variable is updated via logic, the input field reflects the change.
- Two-Way Binding
[(ngModel)]="value": Commonly used in forms. It combines property binding and event binding syntax (the 'banana in a box').
Data Binding Summary
| Type | Syntax | Direction |
|---|---|---|
| Interpolation | {{ expression }} | Component to View |
| Property Binding | [property]="value" | Component to View |
| Event Binding | (event)="handler()" | View to Component |
| Two-Way Binding | [(ngModel)]="property" | Both Ways |