{{announcement.body}}
{{announcement.title}}

Getting Started With Data Binding in Angular 8

DZone 's Guide to

Getting Started With Data Binding in Angular 8

In this article, we discuss how to perform one and two-way data binding in Angular to understand how to communicate between components and views.

· Web Dev Zone ·
Free Resource

Introduction

In this article, we will learn about data binding in Angular. As we know, Data Binding is used for binding data from a View to a Component or from a Component to a View.

One-Way Data Binding

In one-way data binding, we have different ways of binding data from our Component.ts class file to our  Component.html file:

  • String Interpolation.
  • Property Binding.
  • Style Binding.
  • Class Binding.
  • Attribute Binding.

In order to pass data from our Component.html file (View) to our Component.ts class, we use Event Binding.

String Interpolation

In String Interpolation we bind the data from a Component.ts class file to Component.html file by using the expression in double curly braces. If we don't pass the data or the component's field in double curly braces, then Angular treats this as a string value and displays the string value to the end-user. 

Open the Component.ts file and add the following code:

    TypeScript




    x
    44


     
    1
    export class Test3Component implements OnInit {    
    2
       firstName: string = 'Khaja';    
    3
       lastName: string = 'Moizuddin';    
    4
       number1: number = 100;    
    5
       number2: number = 200;    
    6
       totalAmount: number = this.number1 + this.number2;    
    7
       fullName: string = this.firstName + this.lastName;    
    8
       fullNameVal:string;    
    9
       totalVal:number;    
    10
       csharpCornerURL: string = 'https://www.c-sharpcorner.com/members/khaja-moiz';    
    11
       myImagePath: string = 'assets/Images/mvp1.jpg';    
    12
       heightImg: number = 50;    
    13
       widthImg:number = 50;    
    14
       onButtonClick: string;    
    15
       onDoubleClick: string;    
    16
        
    17
      getTotalAmount1() {    
    18
        return this.number1 + this.number2;    
    19
     }    
    20
      getTotalAmount2() {    
    21
    return this.totalVal = this.number1 + this.number2;    
    22
      }    
    23
      getTotalAmount3() {    
    24
       return this.totalVal = this.totalAmount;    
    25
      }    
    26
      getFullName1() {    
    27
        return this.firstName + this.lastName;    
    28
      }    
    29
      getFullName2() {    
    30
     return this.fullNameVal = this.firstName + this.lastName;    
    31
      }    
    32
      getFullName3() {    
    33
        return this.fullNameVal = this.fullName;    
    34
      }    
    35
      onBtnClick() {    
    36
    return this.onButtonClick = 'Welcome ' + this.firstName;    
    37
      }    
    38
      onDblClick(){    
    39
        return this.onDoubleClick = 'Welcome ' + this.lastName;    
    40
      }    
    41
    constructor() { }    
    42
      ngOnInit() {    
    43
      }    
    44
    }    



Now, open the Component.html file and add the following code:

    TypeScript




    xxxxxxxxxx
    1
    14


     
    1
    <h2>STRING INTERPOLATION</h2>    
    2
    <hr>    
    3
    <h3> firstName is:{{this.firstName}}  </h3>    
    4
    <h3> lastName is: {{this.lastName}} </h3>    
    5
    <h3> fullName is:{{this.fullName}}  </h3>    
    6
    <h3> fullName1 is:{{this.getFullName1()}}  </h3>    
    7
    <h3> fullName2 is:{{this.getFullName2()}} </h3>    
    8
    <h3> fullName3 is:{{this.getFullName3()}}  </h3>    
    9
    <h3> Number1 is : {{this.number1}} </h3>    
    10
    <h3> Number2 is:{{this.number2}}  </h3>    
    11
    <h3> TotalAmount is:{{this.totalAmount}}  </h3>    
    12
    <h3> TotalAmount1 is:{{this.getTotalAmount1()}}  </h3>    
    13
    <h3> TotalAmount2 is:{{this.getTotalAmount2()}}  </h3>    
    14
    <h3>TotalAmount3 is: {{this.getTotalAmount3()}}  </h3>    



In the code above, we used double curly braces for binding the data from the Component.ts class to our Component.html file; with this, it converts the field values as an expression. 

You may also like: Angular Data Binding for .NET Developers.

The expressions:

Java




xxxxxxxxxx
1


 
1
fullName: string = this.firstName + this.lastName; or totalAmount: number = this.number1 + this.number2;


 
converts the values as an expression and returns the result to the end-user.

Property Binding 

In Property binding, we bind data from our Component.ts class to the Component.html file. The HTML elements property is bound with the values from the Component.ts file using square brackets []

Now, open the Component.html file and add the following code:

    HTML




    xxxxxxxxxx
    1


     
    1
    <span [innerText]='this.firstName'></span><br>    
    2
    <span [innerHTML] = 'this.lastName'></span><br>    
    3
    <span innerText = '{{this.firstName}}'></span><br>    
    4
    <span innerHTML = '{{this.lastName}}'></span> 



In the above code, we used [innerHTML] and [innerText], which is nothing but property binding. Here, the values this.firstName,  this.lastName are bound from the Component.ts file. The output will be visible to the end-user and placed in between the span tags.

    HTML




    xxxxxxxxxx
    1


     
    1
    <!--BINDING PROPERTY TO DOM ELEMENT-->    
    2
    <span [attr.innerText]='this.firstName'></span><br>    
    3
    <span [attr.innerHTML] = 'this.lastName'></span><br>    
    4
    <span attr.innerText = '{{this.firstName}}'></span><br>    
    5
    <span attr.innerHTML = '{{this.lastName}}'></span>

     


With the above code, we used the attr attribute, which is nothing but attribute binding with a property name that binds the Component's value to the DOM element. The output will not be visible to the end-user, but the innerText and innerHTML properties will be added to the span tags, which can be shown below. 

    HTML




    xxxxxxxxxx
    1


     
    1
    <a href="{{this.csharpCornerURL}}" target="_blank">CsharpCorner</a><br>    
    2
    <a [href]='this.csharpCornerURL' target="_blank">CsharpCorner</a><br>    
    3
    <$$anonymous$$ttr.href = '{{this.csharpCornerURL}}' target="_blank">CsharpCorner</a><br>    
    4
    <a [attr.href]='this.csharpCornerURL' target="_blank">CsharpCorner</a><br>    
    5
    <img src='{{this.myImagePath}}' height='{{this.heightImg}}' width="{{this.widthImg}}" /><br>    
    6
    <img [src]='this.myImagePath' [height]='this.heightImg' [width]="this.widthImg"><br>    
    7
    <img attr.src = '{{this.myImagePath}}' attr.height='{{this.heightImg}}' attr.width="{{this.widthImg}}"><br>    
    8
    <img [attr.src]='this.myImagePath' [attr.height]='this.heightImg' [attr.width]="this.widthImg">    



Here, I have used different ways of binding the Component's value to the href and src properties, as shown in the above code.

Style Binding

Using Style Binding, we can set the style using the [ngStyle] attribute by passing the value to the Component.ts file. Here, I am going to set the [ngStyle] attribute with background color with the following conditions: If the condition is successful, then I am going to display the background color as green, and if the condition fails then I am going to display the background color as red.

Open the Component.html file and add the following code:

    HTML




    xxxxxxxxxx
    1
    14


     
    1
    <h2>NG STYLE WITH TRUE CONDITION</h2>    
    2
    <h3 [ngStyle]="{'background-color': this.fullName == this.getFullName1()?'green':'red'}">NG STYLE WITH TRUE CONDITION</h3>    
    3
    <h3 [ngStyle] = "{'background-color': this.getFullName1() == this.getFullName2()?'green':'red'}">NG STYLE WITH TRUE CONDITION</h3>    
    4
    <h3 [ngStyle] = "{'background-color': this.getFullName3() == this.firstName + this.lastName ?'green':'red'}">NG STYLE WITH TRUE CONDITION</h3>    
    5
    <h3 [ngStyle] = "{'background-color': this.totalAmount == this.getTotalAmount1() ?'green':'red'}">NG STYLE WITH TRUE CONDITION</h3>    
    6
    <h3 [ngStyle] = "{'background-color': this.getTotalAmount2() == this.getTotalAmount3()?'green':'red'}">NG STYLE WITH TRUE CONDITION</h3>    
    7
    <h3 [ngStyle] = "{'background-color': this.getTotalAmount3() == this.number1 + this.number2?'green':'red'}">NG STYLE WITH TRUE CONDITION</h3>    
    8
    <h2>NG STYLE WITH FALSE CONDITION</h2>    
    9
    <h3 [ngStyle]="{'background-color': this.fullName != this.getFullName1()?'green':'red'}">NG STYLE WITH FALSE CONDITION</h3>    
    10
    <h3 [ngStyle] = "{'background-color': this.getFullName1() != this.getFullName2()?'green':'red'}">NG STYLE WITH FALSE CONDITION</h3>    
    11
    <h3 [ngStyle] = "{'background-color': this.getFullName3() != this.firstName + this.lastName ?'green':'red'}">NG STYLE WITH FALSE CONDITION</h3>    
    12
    <h3 [ngStyle] = "{'background-color': this.totalAmount != this.getTotalAmount1() ?'green':'red'}">NG STYLE WITH FALSE CONDITION</h3>    
    13
    <h3 [ngStyle] = "{'background-color': this.getTotalAmount2() != this.getTotalAmount3()?'green':'red'}">NG STYLE WITH FALSE CONDITION</h3>    
    14
    <h3 [ngStyle] = "{'background-color': this.getTotalAmount3() != this.number1 + this.number2?'green':'red'}">NG STYLE WITH FALSE CONDITION</h3> 



Class Binding

Using Class Binding, we can set the ngClass attribute. With the [ngClass] attribute, we can set the class property of the HTML element and set the CSS for the applied value for the  [ngClass] attribute.

Open the Component.html file and add the following code:

    HTML




    xxxxxxxxxx
    1


     
    1
    NG CLASS EXAMPLE1: <input type="text" [ngClass]= 'this.fullName' [id]='this.firstName' [name]='this.lastName'/><br>    
    2
    NG CLASS EXAMPLE1: <input type="text" ngClass= '{{this.fullName}}' id='{{this.firstName}}' name='{{this.lastName}}'/><br><br>        
    3
    NG CLASS EXAMPLE2: <input type="text" [attr.ngClass]= 'this.fullName' [attr.id]='this.firstName' [attr.name]='this.lastName'/><br>    
    4
    NG CLASS EXAMPLE2: <input type="text" attr.ngClass= '{{this.fullName}}' attr.id='{{this.firstName}}' attr.name='{{this.lastName}}'/><br><br>    
    5
    CLASS EXAMPLE3: <input type="text" [class]= 'this.fullName' [id]='this.firstName' [name]='this.lastName'/><br>    
    6
    CLASS EXAMPLE3: <input type="text" class= '{{this.fullName}}' id='{{this.firstName}}' name='{{this.lastName}}'/><br><br>    



The examples explained above are one-way data-binding from the Component.ts class file to the Component.html file or View.

Event Binding 

It is one-way data binding, which is binding the value from the Component.html file to the Component.ts class file, or View to Component.

Open the Component.html file and add in the following code:

    HTML




    xxxxxxxxxx
    1


     
    1
    <h2>EVENT BINDING</h2>    
    2
    <hr>    
    3
    <input type="button" (click)=onBtnClick() value="CLICK" height="20" width="20">    
    4
    <h3>{{this.onButtonClick}}</h3>    
    5
    <input type="button" (dblclick)=onDblClick() value="DOUBLE CLICK" height="20" width="20">    
    6
    <h3>{{this.onDoubleClick}}</h3>

       


Here, when a user clicks or double clicks on a button in the View, we are setting the value this.onButtonClick and this.onDoubleClick in  onBtnClick() and  onDblClick() methods and displaying the result or message to the end-user below the Click and Double click buttons. 

Two-Way Data Binding

In two-way data binding, the data can be bound from the Component.html file to the Component.ts class or from the Component.ts class to the Component.html file.

If the textbox value in the View changes, then the Component.ts value also gets reflected; similarly if we change the Component.ts value, then the textbox value gets reflected.

In two-way data binding, we use the [(ngModel)] attribute. We also need to import the FormsModule in the app.Module.ts file like so:

    TypeScript




    xxxxxxxxxx
    1


     
    1
    import {FormsModule} from '@angular/forms';    



and add the FormsModule in the imports array. 

    JSON




    xxxxxxxxxx
    1


    1
    imports: [    
    2
        BrowserModule,    
    3
        AppRoutingModule,    
    4
        FormsModule    
    5
     ],  


 
Open the Component.html file and add the following code:

    HTML




    xxxxxxxxxx
    1


     
    1
    Two Way Binding: <input type="text" [(ngModel)]='this.fullName' value="{{this.fullName}}">    
    2
    {{this.fullName}}   



With this, if the Textbox value changes, then the Component.ts field, this.FullName changes. Additionally, if we change the  this.fullName field, then its new value will be reflected in the TextBox.


Further Reading

Topics:
databinding ,angular 8 ,web dev ,two-way ,one-way ,tutorial

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}