Data Binding in Angular Component

In Angular, component contains typescript (where we write a code logic) and html (template code) files. To access the data between typescript and html code data binding is used and this Data Binding is mainly of two types -

  1. One way data binding - where data is passed only in one direction or way(i.e. either from typescript code to html element or from html element to typescript code).
  2. Two way data binding - data is sent in both the ways(that is from typescript code to html element and html element to typescript code).

Let's discuss about One way data binding first -
One way data binding could be of below types -

  • String Interpolation - Binds the value stored in variable as a string in html code, this data binding is from typescript file to html template. Double Curly Braces i.e. {{}} are used for String Interpolation. For Example, refer below code -

In product-details.component.ts file -

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

            @Component({
              selector: 'app-product-details',
              templateUrl: './app-product-details.component.html',
              styleUrls: ['./app-product-details.component.css']
            })
            export class ProductDetailsComponent {
                title: string = 'Product Details';
                productName : string = 'Notebook';
            }

In product-details.component.html file -

            <div class="form-container">
              <div class="login-form">
                <h3>{{title}}</h3>
                <div>
                  <label>Product Name</label><span>:</span>
                  <input class="login-form-content" value="{{productName}}" />
                </div>
              </div>
            </div>

It's output will be like -

string_interpolation.png

Here we are binding title and productName in html template.

  • Property Binding - Binds a value stored in a variable to some html element, this data binding is from typescript file to html template. Square brackets i.e [] are used for Property Binding. Let's take an example, i want to bind a default value to an input element -

In product-details.component.ts file -

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

            @Component({
              selector: 'app-product-details',
              templateUrl: './app-product-details.component.html',
              styleUrls: ['./app-product-details.component.css']
            })
            export class ProductDetailsComponent {
                title: string = 'Product Details';
                productName: string = 'Notebook';
                amount! : number;
            }

In product-details.component.html file -

            <div class="form-container">
              <div class="login-form">
                <h3>{{title}}</h3>
                <div>
                  <label>Product Name</label><span>:</span>
                  <input class="login-form-content" [value]="productName" />
                </div>
                <div>
                  <label>Amount</label><span>:</span>
                  <input class="login-form-content" [value]="amount" type="number"/>
                </div>
              </div>
            </div>

It's output will be like -

property_binding.png

In output, you can see Product Name input field is by default showing "Notebook" as a value in it.

Note - Difference between String Interpolation and Property Binding - String Interpolation always considers value as a string whereas Property Binding preserves the data type for value. Property Binding is used when data type of value is important.

  • Event Binding - this is used for binding the events of html element. For example, consider a change event for a Product Name input, On value change event of input, if we want to store the data in typescript variable then we can use Event binding. Here we bind a method to particular event. In this case data flows from html template to Typescript code. Round Brackets i.e. () are used for Event Binding.

    In above example, when user updates/changes Product Name input in form, using property binding we will not be able to get updated value in productName variable to do so we need to add event binding -

    <input class="login-form-content" [value]="productName" (change)="onProductNameChange($event)" />
    
        onProductNameChange(event: any){
          this.productName = event.target.value;
        }
    

    Now, every time the change event will be triggered, it will update the value in productName.

In similar way, we can use built-in events (like click, keyup, keydown, etc) as well as custom events.

As in Two way binding, data flows in both direction, brackets used for two way binding are combination of Property and Event Binding i.e [()].

In above example, we seen that we want two way binding means i want to show a default value(stored in productName variable) in Product Name field also if user changes the value in this field it should also get reflected in productName variable. And in above Event Binding example, we added property binding as well as event binding on same input field, instead of this we can simply use two way binding instead of two different bindings as follows -

In product-details.component.html file -

        <div class="form-container">
          <div class="login-form">
            <h3>{{title}} : {{productName}}</h3>
            <div>
              <label>Product Name</label><span>:</span>
              <input class="login-form-content" [(ngModel)]="productName" />
            </div>
            <div>
              <label>Amount</label><span>:</span>
              <input class="login-form-content" [value]="amount" type="number"/>
            </div>
            <button (click)="saveProductDetails()">Submit</button>
          </div>
        </div>

In product-details.component.ts file -

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

        @Component({
            selector: 'app-product-details',
            templateUrl: './app-product-details.component.html',
            styleUrls: ['./app-product-details.component.css']
        })
        export class ProductDetailsComponent {
          productName : string = 'Notebook';
          amount! : number;

          onProductNameChange(event: any){
            this.productName = event.target.value;
          }

          saveProductDetails(){
            console.log(this.productName);

            //Add submit code here..
          }
        }

Output -

Two_way_binding.png

Note - In this example, we have used ngModel for two way binding, we need to add FormsModule in app.module.ts for using ngModel directive.

Keep Coding!!!

Did you find this article valuable?

Support Pranita's Blogs by becoming a sponsor. Any amount is appreciated!