Angular 5 Property - Event Bindings

Binding is the process which forms the connection between the application UI and the data which comes from the business logic. In Angular it can be called the automatic synchronization of the data and the view.

Binding

It is the process which forms a connection between application UI and data which comes from the business logic. In Angular, it can be called as the automatic synchronization of the data and the View.

Before moving to the main section, let's understand some parenthesis we use in Angular and their meaning and their usage.

  1. {{ expression }}
    These are the interpolation brackets which can be used to directly evaluate the expression an insert them into HTML

  2. () (parenthesis)
    These are used for the events which are raised from the elements, like click, double-click, key up, key down etc. It is followed by = which will be a method in the component that is called on the completion of the event.

    <element (event)="method()"></element>

  3. [] (Square bracket)
    The square bracket is the other way around (). It sets the value from the component to the HTML element DOM Properties.

In Angular, mostly there are 3 types of bindings.

  1. Property Binding
  2. Event Binding
  3. Two-way Binding

Property Binding

Property Binding means we pass the data from the component class and set the value to the given element in the View. This is one way where the data is passed from the component to View.

There are three ways by which we can achieve the property binding. Before understanding the things here, let's add the component in the application using ng generate command. Let's name it as propertybinding.

By using Interpolation

Interpolation is nothing but the way to display the calculated string or value inside the HTML element. How do we use this? In the code, let’s see the code snippet below.

Component

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-propertybinding',  
  7.     templateUrl: './propertybinding.component.html',  
  8.     styleUrls: ['./propertybinding.component.css']  
  9. })  
  10. export class PropertybindingComponent implements OnInit {  
  11.     title: string = "Hello from component."  
  12.     imagepath = 'https://angular.io/assets/images/logos/angular/angular.svg';  
  13.     constructor() {}  
  14.     ngOnInit() {}  
  15. }  

In this component, we have defined one property called imagepath which holds the path of the image which will be shown. In order to use this property in the interpolation, we can use the following code in the View.

  1. <br>   
  2.   <strong>  
  3.     image using the property Binding using interpollation  
  4.    </strong>   
  5.       <br>   
  6. <img src="{{imagepath}}" width="300px" height="150px" alt="image not found">  

In this, we can see that src is directly bound to the source property of the image tag. Angular directly replaces the imagepath with the value set at the component and it will be assigned to the source of the image tag.

Brackets around Element Property

Another most commonly used method for the binding is using the Square brackets. Here, we wrap the element property and assign the component property to this element property.

So as to do this, let's modify the code like below.

  1. <br>  
  2. <strong>Element Property binding using [] </strong>  
  3. <br>  
  4. <img [src]="imagepath" width="300px" height="150px" alt="image not found"

Here, in the above code snippet, what we have done is we have assigned the imagepath from component directly to the src property and for this, we used the [] which assigns the value from the Component to the HTML element. 

Using “bind- “prefix before element property

This is the third way where we can do the property bindings in order to do this we just need to add the ‘bind-‘ as a prefix to the element property.

Let’s see the code snippet for the same.

  1. <strong>Element Property binding using Binding Prefix</strong>  
  2.  <img bind-src="imagepath" width="100px" height="100px" alt="image not found">  

Here, we have prefixed the src of the image element and assigned the imagepath from the component to it and we can see the output on the screen.

Which to use when?

We can use the interpolation until the value we are using from the component is string; otherwise we must use the other 2 methods in order to do the property binding.

Let’s see another case of the disabling the button by using the disabled property of the button. For this add the new property in the component with datatype Boolean and name it as a status.

Code for that is as below,

status:boolean=false;

UI code which will be used for this will be in this the status will be assigned to the disabled attribute of the button.

  1. <p>  
  2.    <button [disabled]="status">Click Me</button>  
  3. </p>   

This was for the property binding with the angular; now it's time to see the Event Binding

Event Binding

All the user interactions with the application happen through the click, double click or hover or may e some key actions such as keypress, key up or key down then generally there will be the case where we will be calling some logic on these actions that’s when the event binding helps us.

Event binding is the one-way data binding which sends the value from the view to the component which is in contrast to the property binding where we used to send the data from component to the view.

Let’s check the basic event binding code that we will see for that we have modified the component as follows .

 

  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-event-binding',  
  7.     templateUrl: './event-binding.component.html',  
  8.     styleUrls: ['./event-binding.component.css']  
  9. })  
  10. export class EventBindingComponent implements OnInit {  
  11.     logevent(event) {  
  12.         alert("Hi");  
  13.     }  
  14.     constructor() {}  
  15.     ngOnInit() {}  
  16. }  

 

As we can see we have one method logevent which logs the events from the button click which is their present in our UI which is like below

 

  1. <button (click)="logevent()">Log</button>  

 

Here whenever the Button click happens then log event method will call the logevent which will greet us with Hi

Simple isn’t it 😊? So what if we need to pass the value of some control from the UI to the method in the component how we can do that? Let's check it step by step.

First of all add one html element in the UI an add following elements in the UI it has the three input elements for the Username ,password and the email and the Button which calls the method which is there in the component.

 

  1. <p>   
  2.   User name <input type="text" #txtUserName><br> password <input type="password" #txtpassword><br> Email <input type="Email" #txtEmail><br>  
  3.   <button(click)="SendData(txtUserName.value,txtpassword.value,txtEmail.value)">  
  4.     SendData   
  5.    </button>  
  6. </p>  

 

Next thing is we need to add the SendData () to the component which will be called On the Button click. So, we modify the component with the following snippet,

 

  1. SendData(Username: string, password: string, emailID: string): void  
  2. {  
  3.     alert("user name " + Username);  
  4.     alert("password " + password);  
  5.     alert("email " + emailID);  
  6. }  

 

So when we click the Button then we can see the alerts with the values we passed in the corresponding textboxes. This is how we can pass the data from the UI to the components.

Next Version of the event Binding is using with the prefix on- before the event of the element

For this just add one more html element like below,

 

  1. <button on-click="SendData(txtUserName.value,txtpassword.value,txtEmail.value)">Click to send Data</button>  

 

We can see here is we have prefixed click event of the button with on- before it so whenever the click happens we will see the same output as before.

These are the Two ways to handle the Event Binding we can sum up this like,

  1. () :: wrap the event in parentheses an assign the method which from the component
  2. on- :: append on- before the event an assign the method from the component which will be called.

    Note
    #txtUsername,#txtpassword are the template reference variable which can be used with the angular to take the values

Two way Binding

What Is two-way binding ?

There might be most of the cases where user will be entering some values and accordingly the UI should be updated so two way helps us with that .Two way binding is the combination Property Binding [] and the Event Binding () so Two way Binding can be used with these combination as

([……]) . It allows continuous sync between the presentation and the View layer of the application.

Let’s understand how we can achieve this. For this let's add the new component, namely TwoWayBinding in the application . Ok now let's see the snippet that we are coding with -- just html file here

 

  1. <hr>  
  2. <h3>Two way Binding.</h3>  
  3. <p> <input type="text" [(ngModel)]="showoutput">  
  4.   <br/> {{showoutput}}  
  5. </p> 

When we save the file and see the output, we can observe that whenever we are typing in textbox, that value will be rendered below it. We are using the two-way binding here since we have used [(..)] brackets. This tells Angular the property which we are assigning is two-way binding.

There are various ways by which we can implement the Two-way data binding using the @input , @output with event emitters which I have shared in the last article which can be found here on the location.

So this was all about the Binding properties and event Binding that we have from Angular.

References

https://angular.io/ 

Note

Please run npm install before running this source code.