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)
Source to View (one-way)
This refers to as Property binding method, it includes all following patterns to share data from source to view.
Interpolation
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>
Property Binding
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>
Attribute, Style and class binding
Attribute bindings
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>
Class binding
Single class binding
[class.sale]="onSale"
Multiple Class bindings
[class]="'my-class-1 my-class-2 my-class-3'"
Styles binding
Single style binding
<nav [style.background-color]="expression"></nav>
Multiple styles binding
<nav [style]="stylesExpression"></nav>
View to Source (one-way)
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()
:
3. View to Source to View (two-way)
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! 💻
Top comments (2)
Good to see you here.
Thanks :)