DEV Community

Cover image for Types of Data Binding in Angular
Ahmed Murtaza
Ahmed Murtaza

Posted on

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.

  1. Source to View (one-way)
  2. View to Source (one-way)
  3. 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>
Enter fullscreen mode Exit fullscreen mode

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> 

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Class binding

Single class binding

[class.sale]="onSale"
Enter fullscreen mode Exit fullscreen mode

Multiple Class bindings

[class]="'my-class-1 my-class-2 my-class-3'"
Enter fullscreen mode Exit fullscreen mode

Styles binding

Single style binding

<nav [style.background-color]="expression"></nav>
Enter fullscreen mode Exit fullscreen mode

Multiple styles binding

<nav [style]="stylesExpression"></nav>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
mahmoodayaz7 profile image
Mehmood Ayaz

Good to see you here.

Collapse
 
ahmedgmurtaza profile image
Ahmed Murtaza

Thanks :)