How to perform data binding in Angular / Hiding HTML elements using Data binding in Angular

What is Data Binding?

A view in an angular application is a component and a component is composed of a component class(written in typescript) and an HTML template. The component class contains properties and methods which represent the data of a component. HTML template of a component can access these properties and methods. As such the properties and methods are frequently used in the HTML template in order to extend its functionality and make it more dynamic. This sharing of component properties into its HTML template is done through Data Binding.

Data Binding : Syntax

Data binding between a component class and its HTML template is done by enclosing the property between double curly braces({{ and }}). When angular encounters these symbols in the template, it replaces the property between them with its string value. This is called Interpolation. Let us understand it through an example.

Suppose there is a component class as shown below

   import { NgModule } from ‘@angular/core‘;  
  
   @Component
({
            selector : ‘<codippa>’,
            templateUrl : ‘./codippa.component.html’,
            providers : [ CodippaService ]
   })
    export class CodippaComponent {
         private String appTitle = “CodippaApp”;
       
         // more code here
   }

The class is a component as visible from @Component annotation which has a single property. Now, take a look at the HTML template of this component.

   <html>
      <body>
              <h1>{{ appTitle }}</h1>
      </body>
   </html>     

This template has the property of component class enclosed between double curly braces. When this template is rendered, the resulting HTML is

   <html>
      <body>
              <h1>CodippaApp</h1>
      </body>
   </html>

Angular replaced the property name with its value.

Interpolation with Expressions

Generally, the text between {{ and }} is a property of component class. But, Angular treats the text between the double curly braces as an expression, evaluates it and converts it into a string. Thus, below expressions are evaluated as shown.

<h1>Heading as a number is {{ 2 + 2 }}</h1>
<!– Rendered as <h1>Heading as a number is 4</h1> –>
<h1>Heading as alphanumeric is {{ a + 2 }}</h1>
<!– Rendered as <h1>Heading as alphanumeric is a2</h1> –>

How Data binding makes the template Dynamic

When properties of a component class are used in its HTML template, then any change in the property value is reflected back in the template. Thus, the HTML template can also be changed after it is rendered. Example, suppose there is a header element(<h1>) in a template whose text is a property of a component as

<h1>{{ appTitle }}</h1>

Now suppose the value of appTitle is “CodippaTemplate“, the tag will be displayed as

<h1>CodippaTemplate</h1>

Now if the value of the property is changed to “UpdatedTemplate“, the tag will be displayed as

<h1>UpdatedTemplate</h1>

Thus making the template dynamic and modifiable at run time. Further, it is also possible to play around with the template elements by displaying them or hiding them as per requirement as shown in the next section.

Show/hide elements in HTML template using Data binding

It is also possible to show or hide elements in an HTML template by binding them with a property of component class. Example, when ordering a pizza, there is an option to add toppings. This is a checkbox and when you wish to add toppings, you click this checkbox. As it is checked, some options appear. As it is unchecked, the options vanish. How this could be implemented in Angular, let’s understand.
Suppose the HTML template is

<p>
    Add toppings   <input type=”checkbox“/>
</p>
<div>
     <span>Extra Cheese</span>
     <span>Extra Onions</span>
     <span>Extra Olives</span>
</div>

It has a checkbox for extra toppings and a div element which has the list of toppings. When the checkbox is checked the div should be displayed and vice-versa. Now how do you implement it in angular First, let us define a component class for the template.

   export class PizzaToppings {
      // property to mark extra toppings required
      private boolean isExtraToppings;
      /*
       * Function which reverses the value of extra toppings property
      */
      private extraToppings(): void {
         this.isExtraToppings = !isExtraToppings;
      }
   }

The above component is a simple class with just one boolean property and one function which reverses the value of this property. If it is true, makes it false and vice-versa. Note that @Component annotation and its meta data have been omitted for simplicity.

Now let’s modify the template to support the required functionality using data binding.

<p>
    Add toppings   <input type=”checkbox(click)=”extraToppings()”/>
</p>
<div *ngIf = “isExtraToppings”>
     <span>Extra Cheese</span>
     <span>Extra Onions</span>
     <span>Extra Olives</span>
</div>

Two changes have been made in the template to support our requirement.
    1. A click event handler is introduced over the check box. This event handler calls the component class function when the check box is clicked.
    2. An if condition is written on the div which we want to show/hide. This if condition checks on the value of isExtraToppings component class property. The div will be visible if the property evaluates to true and it will be hidden if the property evaluates to false.

Initially, the property isExtraToppings is false, so the div is not visible. When the check box is clicked, it calls extraToppings function which changes property value to true and the div becomes visible. When check box is clicked again, the property value is false, div hides again and so on. Thus, the div is bound to the component class property and is more dynamic.
Similar functionality can also be implemented on a button click.

Note: Above example also makes use of a couple of other Angular concepts namely Event Binding(check box click event) and Directives(ngIf). These will be discussed in subsequent posts.

Hope this post clarified the concept of Angular data binding. For any doubts, feel free to add a comment. Keep Visiting !!!