Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Bindings in Angular

DZone's Guide to

Bindings in Angular

In this post, a developer dives into the various ways in which we can use binding in Angular applications for passing data in and out of our UI.

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

What Is Binding?

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.

Before moving to the main section of the article, let's look at some parentheses we use in Angular.

1.{{ expression }}  

These are the interpolation brackets which can be used to directly evaluate the expression and insert them into the HTML.

2. () (parenthesis)

These are used for the events which are raised from the elements. Like click, DoubleClick, key up, key down, etc. The () is then followed by = which will be a method in the component that will be called on the completion of the event.

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


3. [] (Square bracket)  

The square brackets set the value from the component to the HTML element/DOM properties.

In Angular, there are 3 types of bindings:

  1. Property Binding

  2. Event Binding

  3. Two-way Binding

1. 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 that data is passed from the component to the view.

There are three ways by which we can achieve property binding. To start, let's add the component in the application using the ng generate command name it the 'property binding.'

Using Interpolation

Interpolation a way to display a calculated string or value inside an HTML element. How do we use this in code? Let’s look at the code snippet below.

Component:

import {Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-propertybinding',
  templateUrl: './propertybinding.component.html',
  styleUrls: ['./propertybinding.component.css']
})

export class PropertybindingComponent implements OnInit
{
  title:string="Hello from component."
;
  constructor() { }

  ngOnInit() {

  }

}


In this component, we have defined one property called imagepath which holds the path of the image which will be shown.

So, to use this property in the interpolation, we can use the following code in the View:

<br>

<strong>image using the property Binding using interpollation</strong>

<br>

<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.

In this Angular code, we directly replace the imagepath with the value set at the component and it will be assigned to the source of the image tag.

2. Brackets Around the Element Property

Another commonly used method for binding is the use of square brackets. With square brackets, we wrap the element property and assign the component property to this element property.

To do this, let's modify the code to look something like what I've got below:

<br>

<strong>Element Property binding using [] </strong>

<br>

<img [src]="imagepath" width="300px" height="150px" alt="image not found">


In the above code snippet, we have assigned the imagepath from the component directly to the src property. For this ,we used the [], which assigns the value from the component to the HTML element.

3. Using "bind-" Prefix Before Element Property

This is the third way that we can perform property binding. In order to do this, we just need to add the 'bind-' prefix to the element property.

Let’s look at the code snippet for this: 

<strong>Element Property binding using Binding Prefix</strong>

<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 interpolation unless the value we are using from the component is a string, otherwise, we must use the other two methods in order to do the property binding.

Let’s see another case of disabling a button by using the disabled property in the HTML button element. For this, let's add the new property in the component with a boolean datatype and name it status.

The code for this is as below:

status:; 

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

<p>

<button [disabled]="status">Click Me</button>

</p>


This was for working with property binding in Angular. Now it's time to look at event binding.

Event Binding

All the user interactions with the application happen through clicks, double clicks, or hovering or maybe some key actions such as keypress, key up, or key down. Generally, there will be the case where we will be calling some logic on these actions - that’s when 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:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-event-binding',
  templateUrl: './event-binding.component.html',
  styleUrls: ['./event-binding.component.css']
})

export class EventBindingComponent implements OnInit {
  logevent(event)
  {
   alert("Hi");
  }
  constructor() { }
  ngOnInit() {
  }
}


As we can see, we have one method, logevent, which logs the events from the button click. This logic is then inserted into our UI like so:

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


Here, whenever the button is clicked, the logevent 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? Let's examine this, step-by-step.

First of all, add one HTML element in the UI and add the following elements in the UI. It has the three input elements for Username, password, and email, and the button element which calls the method in the component.

<p>

User name  <input type="text" #txtUserName><br>

password <input type="password" #txtpassword><br>

Email  <input type="Email" #txtEmail><br>

<button(click)="SendData(txtUserName.value,txtpassword.value,txtEmail.value)">SendData

</button>

</p>


The next thing we need to add is the SendData() method to the component which will be called when the button is clicked. So, we can modify the component with the following snippet:

SendData(Username: string, password: string, emailID: string): void
{
    alert("user name " + Username);
    alert("password " + password);
    alert("email " + emailID);
}


So when we click the button, we can see the alerts with the values we passed into the corresponding textboxes. This is how we can pass data from the UI to the components.

The next version of event binding I'd like to discuss uses the prefix on- before the event of the element.

For this, just add one more HTML element like below:

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


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

These are the two ways to handle event binding. We can sum this up as:

  1. (): Wrap the event in parentheses and assign the method from the component.

  2. on-: Append on- before the event and assign the method from the component which will be called.

Note: #txtUsername, #txtpassword are the template reference variables which can be used with Angular to take in values.

Two-Way Binding

What Is Two-Way Binding?

There might be some cases where a user enters in some values and the UI will be updated accordingly. There two techniques to help us with that. Two-way binding is the combination of property binding [] and event binding (), so two-way binding can be used by combinging the two, such as: ([……]). This allows for a 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 named TwoWayBinding in the application. Ok, now lets see the snippet that we have - we are coding with just an HTML file here.

<hr>

<h3>Two way Binding.</h3>

<p>

<input type="text"  [(ngModel)]="showoutput">

<br/>

{{showoutput}}

</p>


After we save the file, whenever we are typing in the text box, that value will be rendered below. We are using the two-way binding here so we used the [(...)] brackets. This tells Angular that we are assigning the two-way binding property.

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:
binding ,angular ,web dev ,web application development ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}