Demystified Angular Databinding

Srashti Jain  Print 
15 Aug 2018
27 Aug 2018
Beginner
381

In any web application, data binding is the most important part. To understanding importance data binding let’s have a quick look into basic components of an angular application.

An angular application is made up of declarable classes which are components, directives and pipes. However, angular components contain HTML view, by which user can interact with the application. It mainly has two parts:

HTML Template

It contains view for the component (HTML elements: input, select, button, etc.)

Component Class

It contains logic for component like classes, variables, functions, API calls etc. So, in angular application – the interaction between HTML template and component class can be done very easily through data binding. Also, it provides us with the way to manipulate the DOM value dynamically.

What is Data Binding?

A mechanism for binding data values to HTML elements and turning user activities into actions. Data-binding is responsible for data value updates.

There are different ways by which we can achieve data binding in angular:

  1. Interpolation

  2. Property Binding

  3. Event Binding

  4. Two-Way Binding

Angular Data Binding Syntax

Let’s try to understand all of this one by one:

Interpolation {{…}}

It’s used to weave string value into the HTML element. Use variable name inside the double curly braces "{{ }}".

Example

<h1>Interpolation Example<;/h1> 
Name: {{name}} 
To pay: {{amount * 10}} 
<img src="{{imageUrl}}">

Property Binding […]

It’s used to set the property of the element to a component property value. Use square brackets “[]” to set property binding.

Example

<h1>Property Binding Example</h1>
<img [src]="imageUrl"> 
<button [disabled]="isUnchanged">Cancel is disabled</button>

Event Binding (…)

It’s used to set the event of HTML element.

Example

<h1>Event Binding Example</h1> 
<button (click)="onSave()">;Save</button> 

Two-way Binding [(…)]

It’s also known as Banana in the box "[()]" – the combination of property binding [ ] and event-binding ( ), that said you can display the property and update the same whenever the user makes any changes. It can be done using ngModel.

Example

<input [(ngModel)]="name" > 
Summary

Angular Databinding is the way to do interaction between the view and the class. It can be achieved by using Interpolation, Property Binding, Event Binding and Two-way Binding. However, all of them are used for data binding but at different places.

Hands-on Learning
Free Interview Books
 
+