Angular 4 Basics : Data binding

Data binding is a concept that comes with angular which helps the developer to change the static content of a web application and make the web application more reactive and engaging. Before moving on to how this concept was developed in angular I’ll explain the concept with an example. In the series of “Angular 4 Basics” I’ll be using a simple online shop as a common example. In order to buy something from our online shop we need to first click on the “Shop Now” button in our “Home” page, which will then redirect the user to a list of items that we are planning to sell in our web site.

To implement this feature in our online shop, first we need to define an action for “Shop Now” button, and then we need to redirect the end user to the “Shop” page and then we need to display a set of items that we are going to sell in this online shop. These items are typically not static and we might need to fetch these items from a database and display in this “Shop” page dynamically. These kind of dynamic and user engaging events can be implement by using angular’s data binding feature.

In angular data binding can be divided into 4 different categories namely, String interpolation, property binding, event binding and two way binding. And these four types makes the communication between the business logic (Type Script code) and the View (HTML Code) as shown on the below diagram.

In our previous example of displaying a list of items in the “shop” page, assume that we need to display the names of each and every item in the shop as a list.

In order to do this we have to first fetch the items from the database in our Type Script code and then some how we need to send these data into our HTML code, so that it will be visible to the end user. This is actually one way communication from our Type Script code to our HTML code, and in angular there are two ways to achieve this.

String interpolation

In this way we can actually embed some type script elements into our html code itself. Following is a code snippet from our shopping application.

export class ItemComponent {
itemName: "Item1";
...

This is a code snippet from our item component and as you can see it has a property called “ItemName” which has a default value “item1”. We’ll be discussing how to fetch a list of items from our database later on this series, but for now assume that there is only one item in our shop and we are going to store the name of that item in this variable.

<h4>{{itemName}}</h4>

This is a code snippet from our html template file and we are going to just display the name of our item inside a <h4> tag. As you can see we have put the name of the Type Script property that we created inside “{{}}”. This is called string interpolation in angular and inside our HTML code, we can directly access some elements from our Type Script code and it will display the value of that element in the view like we are going to display the name of the item in our “shop” page. Remember, inside these curly braces we can put any string that will eventually get mapped with a respective typescript element. ex: {{itemName}} , {{‘itemName’}} are also valid.

also we can even invoke typescript functions and the returned value will be displayed in the view. e.g. {{getItemName()}} is also valid

Property Binding

This is another way to achieve one way communication from our Type Script code to HTML code. In here we are actually binding a Type Script property to a HTML property.

export class ItemComponent {
itemName: "Item1";
...

This is a code snippet from our ItemComponent Type Script file and we are going to assume that we have only one item in our shop and we are going to display the name of that item in this “itemName” property.

<h4 [innerText]="itemName" ></h4>

We can achieve the same result as string interpolation with this piece of HTML code. In here [innerText] is basically how we are going to bind an HTML property in angular. the “[]” are going to emphasize that we are going to use property binding in here and then inside the brackets we need to mention what is the HTML element property that we are going to use. In this example we are going to use the innerText property of the h4 element in HTML and there are ton of other HTML properties that we can use in binding. With this innerText property we can actually change the text content of the h4 element and therefore if we assign some text value to this property like this,

innerText="some text"

it is going to get displayed in the view. This is exactly what is happening in here, but instead of assigning a text content we are going to display a dynamic content from the Type Script file. Here also we can either directly assign a variable or else we can invoke a Type Scriptfunction.

e.g. [innerText]=”itemName” and [innerText]=”getItemName()” are also valid.

Event Binding

So far we have discussed one way communication from our Type Script file to our HTML file. In here we are going to discuss how we are going to do the opposite. That means we are going to send some data from our HTML file to our Type Script file. In our previous example we have discussed that we are going to redirect the user from the“home” page to the “shop” page in the application if, user clicks on “shop now” button. This can be implemented with event binding and all you have to do is defining the redirecting logic in the Type Script file and then bind that logic into the “onClick” event of the “shop now” button.

export class HomeComponent {
onClickShopNow() {
// Redirecting logic goes here
  }
...

This is a code snippet from our HomeComponent and here we have created a new function called “onClickShopNow” and we are going to put our redirection logic inside that function(we will be discussing about this redirecting logic later on this series). Now all we have to do is binding this function to our “shop now” button in the HomeComponent HTML file.

<button (click) = "onShopNow()"

It is as easy as shown in this code snippet. In here we are using “()” to indicate angular that we are going to use event binding and we can mention what is the event that we want to bind. In HTML, there are built-in events like “onClick” , “onLoad” etc, but in here we need to mention the event without the prefix “on”. Then we can bind our event to the respective Type Script function like this,

(click) = "onShopNow()"

Also there is a very important argument that we can pass into our type script function which is called $event. We can pass this argument to the function like this.

(click) = "onShopNow($event)"

and the Type Script function should be modified to take this as a parameter in the function definition.

export class HomeComponent {
onShopNow(event) {
// Redirecting logic goes here
}
...

In the HTML file $event is a reserved key word and this will basically sends all the event related information to the type script file so that inside the function we can refer to these information. We’ll be discussing about this event variable and it’s use cases later.

Two Way Binding

Up to now we have discussed about one way communication between our Type Script file and the HTML file and it was sufficient to implement our requirement in the application. In an online shop like our’s it is required to update information of items regularly

e.g. there should be a way to update the unit price of an item.

For the sake of simplicity we’ll assume that there is a requirement to display a “Update Item” page to our admin users of the application where, they can view the old values of the item properties like name, description, price, image URL and then update the properties with the new values. The interface might look like this.

All four properties have an editable text field and initially it will display the current values and user can then edit these values and click on the “update” button to update these values in the database. In order to implement this feature we need to send the current values of these properties from our Type Script file to the HTML file display those values as default values in the text fields and after updating and clicking on the update update button, some how we need to send the updated values from HTML file to Type Script file. As we discussed earlier we can implement this feature by using string interpolation/ property binding + event binding. But with angular we have an elegant way of doing the same thing. We call it the two way data binding. all we have to do is defining the property that we need to bind in our Type Script file and then bind it from the HTML file.

export class ItemComponent {
itemName: "Item1";
...

As shown in this code snippet we are maintaining the name of the item in a property called itemName. Now what we have to do is just bind this property from the HTML file like this,

<input type="text" [(ngModel)] = "itemName"

“[()]” is the syntax that we are telling angular that we are going to use the two way binding in here. If you can remember, we have used “[]” syntax for property binding and “()” syntax for event binding. In here since we are going to combine both the features we are going to use “[()]” syntax and then we need to use a special directive called “ngModel” . We will discuss about directives later and for now just remember that we need to use this directive here. After that all we need to do is mention the property that we need to bind in our Type Script file like this,

[(ngModel)] = "itemName"

Also if we are using the two way data binding for the first time in our app, please remember to import “FormsModule” from the app module.

...
import {FormsModule} from "@angular/forms";
...

@NgModule({
declarations: [...
],
imports: [
FormsModule
],
...
})
export class AppModule { }

If we properly setup this for all our properties of an item in our application, whenever the user navigates to the “Update Item” page, the input fields will have the current values displayed and whenever user types something in these text fields, the value of the respective variable in the Type Script file will be updated accordingly. With this approach we can even implement some cool features like real time validation for our text fields so that each time user types some invalid value in a text field (e.g. entering “ABCD” for price property) we can display an error message without emitting extra events from the HTML file.

Conclusion

I think this was helpful for you to get a basic idea about angular’s data binding features and I’ll be continuously posting more on other important features of angular 4 as well. Happy Coding Everyone!!! :)