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

Simplifying Custom Two-Way Data Binding in Angular 2

DZone's Guide to

Simplifying Custom Two-Way Data Binding in Angular 2

To simplify things, Angular 2 doesn't have built-in two-way data binding. But come on – we can't think of creating a modern web application without the power of two-way data binding.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

There are three types of data bindings in Angular 2:

  1. Interpolation
  2. Event binding
  3. Property binding

If you are coming from Angular 1.X background, you might be wondering where the two-way data binding is. Remember the first time you saw an AngularJS 1.X demo and you were just blown away by the power of ng-model? Yes, like you, I was also very impressed by the power of two-way data binding in AngularJS 1. Even though AngularJS 1 two-way data binding was beautiful, it came with the baggage of digest cycle and $watch.

To simplify things, Angular 2 does not have any built-in two-way data binding. This does not mean you cannot have two-way data binding in Angular 2 applications. Come on, we can't think of creating a modern web application without having the power of two-way data binding.

In this post, we are going to learn how to work with two-way data binding in Angular 2.

Two-Way Data Binding With ngModel

Angular 2 provides us with a directive ngModel to achieve two-way data binding. It is very simple and straightforward to use ngModel directive, as shown in the listing below:

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

@Component({
    moduleId:module.id,
    selector:'my-app',
    template:`
  <div class="container">
     <input [(ngModel)]='name' />
      <br/>
      <h1>Hello {{name}}</h1>
  </div>
  `
})
export class AppComponent{


}

To use ngModel directive, we need to import FormsModule in the application:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

@NgModule({
    imports:      [ BrowserModule,FormsModule ],
    declarations: [ AppComponent],
    bootstrap:    [ AppComponent ]
})
export class AppModule { }

In above demo, when typing into the input element, the input’s value will be assigned to a name variable and displayed back to the view. We are implementing two-way data binding using ngModel as shown in the below image:

Two-Way Data Binding Without ngModel

To understand ngModel directive working, let's see how we can achieve two-way data binding without using ngModel directive. To do that, we need to use:

  • Property binding to bind the expression to the value property of the input element. In this demo, we are binding name variable expression to value property.  
  • Event binding to emit an input event on the input element. Yes, there is an input event that will be fired whenever the user inputs the input element. Using event binding, the input event would be bound to an expression.

Using property binding and the event binding, two-way data binding can be achieved as shown in the listing below:

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

@Component({
    moduleId:module.id,
    selector:'my-app',
    template:`
  <div class="container">
     <input [value]="name" (input)="name=$event.target.value" />
      <br/>
      <h1>Hello {{name}}</h1>
  </div>
  `
})
export class AppComponent{

        name : string = "";
    }

Like the ngModel directive demo in this demo, when typing into the input element, the input element’s value will be assigned to name variable and displayed back to the view. We are implementing two-way data binding without using ngModel using the code shown in the below image:

Let's understand a few important things here:

  • [value]=“name” is the property binding. We are binding the value property of the input element with the variable (or expression) name.
  • (input)=“expression” is the event binding. Whenever the input event is fired, the expression will be executed.
  • “name=$event.target.value” is an expression that assigns the entered value to the name variable.
  • The name variable can be accessed inside the AppComponent class.

So far, we have seen two-way data binding with ngModel and without ngModel. We can conclude that the directive ngModel is nothing but a combination of property binding and event binding. Event binding is denoted using small brackets and property binding is denoted using square [] brackets. If you notice, the syntax of ngModel is [(ngModel)]. It suggests it is a combination of both event and property binding.

Custom Two-Way Data Binding

We should be very careful whether to create a custom two-way data binding or rely on the ngModel directive. We really don’t always have to create custom two-way data binding. However, it is good to know steps to create a custom two-way data binding. Let's create a custom counter component with two-way data binding enabled.

Step 1

Create a component with two buttons and methods to increment and decrement.  

@Component({
    moduleId: module.id,
    selector:'countercomponent',
    template:`
    <button (click)='increnent()'>Increment</button>
    {{count}}
    <button (click)='decrement()'>Decrement</button>
    `
})
export class  AppChildComponent {

        count : number = 0;      
        increment(){

            this.count = this.count+1; 
        }

        decrement(){
            this.count = this.count - 1; 
        }
    }

Above, we have created a very simple component to increment and decrement the count. Now, we can use this component inside another component. However, two-way data binding is not enabled. To enable that, we need to use @Input and @Output properties.

Step 2

Let us create a getter with @Input() property. This getter will return the count. Since it is attributed with @Input() decorator, the consumer of this component can bind this value using property binding.

@Input() get counter(){ return this.count; } 

Step 3

To create two-way data binding, we need to create an event of the type EventEmitter. This event is attributed with @Output() decorator such that it can be emitted to the consumer component. We create an event object in the constructor of the component.

@Output() counterChange :  EventEmitter<number>;
    constructor(){

        this.counterChange = new EventEmitter();

    }

Step 4

As a last step, increment and decrement functions should emit the counterChange event. We need to modify increment and decrement function as shown in the listing below:

   increment(){
        this.count = this.count+1; 
        this.counterChange.emit(this.count);
    }

    decrement(){
        this.count = this.count - 1; 
        this.counterChange.emit(this.count);
    }

Both functions are emitting the counterChange event. Putting the pieces together, a component with custom two-way data binding will look like the code listed below:

import {Component,Input,Output,EventEmitter} from '@angular/core';

@Component({
    moduleId: module.id,
    selector:'countercomponent',
    template:`
    <button (click)='increment()'>Increment</button>
    {{count}}
    <button (click)='decrement()'>Decrement</button>
    `
})
export class  AppChildComponent {

        count : number = 0;   

     @Output() counterChange :  EventEmitter<number>;
        constructor(){
            this.counterChange = new EventEmitter();
        }

     @Input() 
        get counter(){
            return this.count; 
        }

        increment(){
            this.count = this.count+1; 
            this.counterChange.emit(this.count);
        }

        decrement(){
            this.count = this.count - 1; 
            this.counterChange.emit(this.count);
        }
    }

Step 5

Like any simple component, a component with two-way data binding can be used inside another component.

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

@Component({
    moduleId:module.id,
    selector:'my-app',
    template:`
  <div class="container">
     <br/>

     <countercomponent [(counter)]="c"></countercomponent>
     <br/>
     <h2>count = {{c}}</h2> 

  </div>
  `
})
export class AppComponent{

        c : number = 1; 

    }

The main thing you may want to notice by way of the value of the counter property is what we've set inside AppComponent. Like ngModel directive, the counter property is also set using the banana in box syntax [(counter)].

Conclusion

Two-way data binding in Angular 2 is supported using the event and the property binding. We can use ngModel directive to use two-way data binding. Also, if required, custom two-way data bindings can be created. Custom two-way data binding is useful in form controls.

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

Topics:
angular 2 ,data binding ,web dev

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}