Learn About Angular Bindings - Part Two

Introduction

This article demonstrates how to configure various types of binding in Angular. This article starts with Event Data binding. After that, it demonstrates Two-Way Binding, Event Emitter, Input and Output properties with a source-code explanation. In the end, the article discusses ngModel. Kindly refer to my old article Angular Bindings part one to understand other bindings Interpolation and Property Binding.

DataBinding types, which you have come across, are Interpolation and Property Binding. In both of these cases, the data flows from a component to an element. Look at the below source code. The data flow happens in one direction from Component(sCSharpImgURL) to element( [src] )

<img [src]="sCSharpImgURL" style="height:130px" /> <br />

In Event Databinding, the concept is a little different than Property Binding. Here, the data flows from an element to a component. This is a usual case in any UI application when a user clicks a command button, moves a mouse, clicks the particular key in a keyboard the event triggers, and calls the appropriate method we need to handle it as per the application requirement.  The same set of functionalities can also be implemented in Angular. Look at the below source-code.

<button (click)="onSave()">Save Temp</button>

The binding listens for the click events and calls OnSave method once the button clicked. Event name inside the brackets identifies the target OnSave method and calls it.

$event 

When an event is raised, the handler executes the method and sends back the response. When an event gets raised, how are we going to pass the parameters to the handler? In certain situations, we may have to send few parameters to the target method once the event raised. With that parameter information, only the target method will process.Who will carry that information? Yes, the $event does this job. The  $event will communicate all the information like event and data values from the event handler to the component or element according to the target. Let’s see one more example in Event Binding. Have a look at this source-code.

<input [value]="EmployeeCurrentObj.EmployeeName" (input)="EmployeeCurrentObj.EmployeeName=$event.target.value" />

This source-code sets the value property with EmployeeName when the value property gets changed from EmployeeName ‘Rameshkartik’ to ‘Rajesh’, the input event who is listening for the changes will get notified about the change through $event.target.value and the changed value will get updated into EmployeeName. The Attached source-code will give a better understanding.

Event Emitter

The magic of directives creates an emitter and exposes a property. What’s an emitter?

The general meaning of emitting is “Produce and Discharge” which means a person is capable of producing something and discharging it in a different form.  If you apply the same “Produce and Discharge” meaning into the technical stuff – Angular, you would understand the Event Emitter. Assume that one instance is responsible or capable of listing the collection of objects(For Ex: Employees) into a grid structure. Each item in the grid is an Employee object which has EmployeeName, EmployeeCode and EmployeeSalary. And the entire collection is called Employees. And if the user wants to Select a particular row value or select a particular Employee Object, the user clicks the Select link which is available on every row to fetch the Employee Object. As soon as, the user clicks the Select Link, the directive calls EventEmitter.emit to fire an event, the emitter object will emit the particular row Employee object.  Have a look at this source- code, you will get a better understanding.

  1. <grid-ui [grid-Data]="Employees"  
  2.              [grid-entity]="Employee"  
  3.              (grid-output)="Select($event)">  
  4. </grid-ui>  

grid-ui is a directive here, which has properties of grid-Data, grid-entity, grid-output. Leave the first two properties, I will explain to you in the next section of this article. Just look at grid-output property which is mentioned between the square brackets (….). If the property mentioned in the square bracket, the data flow will be from UI element to  component, Once the select link clicked the event will get triggered at the Select method in component and fetches the emitted object from the emitter.

  1. @Output("grid-output") selected:EventEmitter<Object> = new EventEmitter<Object>();  
  2. Select(_selected: Object) {this.selected.emit(_selected); 

 

Look at the source-code above. you can find the same in the EmployeeComponent. As soon as the select method gets fired in the component, it just emits selected Employee object.

Two-Way Binding (  [(…)]    )

Two-way binding is something when a user makes changes the input values, the corresponding property also gets changed. When the property gets changed the UI values also get changed. Both the sides left and right sides get updated when you are making changes anywhere. This is called Two-way Binding. You can implement Two-way Binding with or without ngModel.

Two-way binding with ngModel

Angular 2 does not have a built-in Two-way binding, but it can be achieved by using ngModel. Have a look at the below source-code.

Employee Name

<input [(ngModel)]="EmployeeCurrentObj.EmployeeName " id="Text1" type="text" /> <br />

You are typing Employee Name

{{EmployeeCurrentObj.EmployeeName}} <br />

Whatever the value you are typing into the input control, the value will be assigned to EmployeeName and also it would be displayed back to the View. From the source-code given above, you can find that, When the user is typing EmployeeName in the UI control, the value will be assigned to Employee and it would be displayed back to the View.Please refer to the attached source-code to get more details.

Two-way binding without ngModel

Let me explain the steps to configure Two-way binding without ngModel. The below example will explain the combination of Property Binding and Event Binding [(…)]. [] square brackets will do the property binding and () will do the event binding.

Have a look on this source-code which helps you to understand the Two-way binding (without ngModel) easily. I have created a component called TempConversionComponent which is responsible for converting the Fahrenheit values into Celsius values. TempConversion is a method which will do the conversion using the formula mentioned and emits the output.

output

Look at the Template Element which shows the button has been created and TempConversion method will be triggered when you click the button.

Please refer to my article ‘Learn about Angular Components’ to know how to create components and configure it. Next, I want you to understand the Input and Output properties in the TempConversionComponent. Input properties receive data values, Output properties exposes event producers such as EventEmitter objects.

The following is the code which bounds the TempConversionComponent using Input and Output properties.

Input

<TempConvertor-ui [(valueToBeConverted)]="farheitValue" (valueChange)="farheitValue=$event"></TempConvertor-ui>

Output

valueToBeConverted is an input property which receives values from farheitValue property. valueChange is an output property which sends out the value from the property to the event handler.

  1. @Input() valueToBeConverted: number ;  
  2. @Output() valueChange = new EventEmitter<number>();  

Using the Input decorator @Input, you can define which is the input property in the component. In our case, valueToBeConverted is an input property which receives values from the user interface. Using the Output decorator @Output, you can define which is the output property in the component. In our case, valueChange is an  output the property which sends out the value from the property to the event handler.

<TempConvertor-ui [(valueToBeConverted)]="farheitValue" (valueChange)="farheitValue=$event"></TempConvertor-ui>

The ngModel data property [valueToBeConverted] sets the value property and the ngModelChange event property listens for the changes in the value property.

So the farheit value will set to the input property valueToBeConverted. Then, once the user clicked the button, the TempConversion method will get fired and do the conversion using the input property valueToBeConverted. After that, the converted value will be emitted using the  Output property valueChange to the event handler and it's again updated into farheitValue. This is a desugar syntax for a  property and an event binding. The following is the syntactic sugar for a property and an event binding. Both does the same functionality

<TempConvertor-ui [(valueToBeConverted)]="farheitValue"></TempConvertor-ui>

Kindly refer the attached source-code for more details.

Points to Remember 

  • The target of the binding will be in the left side of =
  • The source of the binding will be in the right side of =
  • The target of a binding is a property or event inside the brackets or braces [], (). [()]
  • The source of the binding is either inside of the “ ” or {{..}}
  • To define the Event Emitter, you have to define both the Input and Output properties

Source-Code 

Please use the link to download the source-code

Summary

Two-way Data binding is the most convenient data binding as it includes both the property and event binding. You can implement Two-way binding using ngModel and without using ngModel. The input and output properties should be applied if you use Event Emitter.