20
Types of Data Binding in Angular
Data binding is the automatic synchronization of data between model and view. In Angular, we have 3 fundamental ways to make to-and-fro binding between view and source.
- Source to View (one-way)
- View to Source (one-way)
- View to Source to View (two-way)
This refers to as Property binding method, it includes all following patterns to share data from source to view.
Interpolation refers to embedding expressions into markup text. By default Angular interpolation uses {{
and }}
to encapsulates the expression.
<p>{{title}}</p>
<div><img src="{{itemImageUrl}}"></div>
The []
brackets cause Angular to consider right-hand side value as dynamic, without brackets Angular evaluates the right-hand value as static string.
<img [src]="itemImageUrl">
<app-item-detail childItem="parentItem"></app-item-detail>
Apart from element properties, we have element attributes ARIA and SVG for which we can use attribute bindings:
<button [attr.aria-label]="actionName">{{actionName}} with Aria</button>
Single class binding
[class.sale]="onSale"
Multiple Class bindings
[class]="'my-class-1 my-class-2 my-class-3'"
Single style binding
<nav [style.background-color]="expression"></nav>
Multiple styles binding
<nav [style]="stylesExpression"></nav>
More specifically, we call this Custom Event binding, utilizing Angular Event Emitter.
Consider the following code showing button which alerts on click. The alert content is passed through <app-button>
component template using custom event showMessage()
:
Angular two-way data binding is the combination of square brackets []
and parentheses ()
. [()]
refers to property binding followed by event binding.
<app-sizer [(size)]="fontSize"></app-sizer>
So, which methods you have already used or would love to use soon, or something else? And Why? Let me know in the comments section. 😃
See you again in another exciting article. Until then, happy coding! 💻
20