Menu Close

Two Way Data Binding in Angular

In this article we will learn about Two Way Data Binding in Angular. The two way data binding implements the two-way binding in Angular Forms. The Two-way binding uses the syntax [()]. Please read my previous article Event binding in Angular.

What is Two way data binding?

The most popular and widely used data binding mechanism in Angular Application is two-way data binding. The two-way data binding is basically used in the input type filed or any form element where the user type or provide any value or change any control value on the one side and on the other side, the same automatically updated into the component variables and vice-versa is also true.

Two way data binding means that changes made to our model in the component are propagated to the view and that any changes made in the view are immediately updated in the underlying component data.

What Scenario Two way Data binding is Required?

Two way data binding is useful in data entry forms. Whenever a user makes changes to a form field, we would like to update our model. Similarly, when we update the model with new data, we would like to update the view as well

The two way data binding is nothing but both property binding & event binding applied together. Property Binding is one way from component to view. The event binding is one way from view to component. If we combine both we will get the Two-way binding.

two-way-data-binding-in-angular

The two-way data binding in Angular is the combination of Event binding and Property Binding using [(ngModel)].

Two way binding using property & Event Binding

Let’s discuss first how we can get two-way data binding using Event binding and Property Binding then we can see how it bind using [(ngModel)].

<input type="text" [value]="name" (input)="name=$any($event.target).value">
<p> You entered {{name}}</p>
<button (click)="clearName()">Clear</button>
export class AppComponent {
 name=""
 clearName() {
   this.name="";
 }
}
two-way-data-binding
$event.target.value raises the error

The error is due to the fact that the value property is not guaranteed to exist in the $event.target.


To solve this problem either you can use the $any typecast function ($any($event.target).value) to stop the type checking in the template or set fullTemplateTypeCheck to false in tsconfig.json.

Two-way binding syntax

The above example uses the event & property binding combination to achieve the two-way binding. But Angular does provide a way to achieve the two-way binding using the syntax [()]. Note that both square & parentheses are used here. This is now known as Banana in a box syntax. The square indicates the Property binding & parentheses indicates the event binding.

<someElement [(someProperty)]="value"></someElement>

What is ngModel?

The Angular uses the ngModel directive to achieve the two-way binding on HTML Form elements. It binds to a form element like input, select, select area. etc. Internally It uses the ngModel in property, binding to bind to the value property and ngModelChange which binds to the input event.

How to use ngModel

The ngModel directive is not part of the Angular Core library. It is part of the FormsModule library. You need to import the FormsModule package into your Angular module. In the template use the following syntax.

The ngModel directive placed inside the square & parentheses as shown above. This is assigned to the Template Expression. Template Expression is the property in the component class

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

Two Way Data binding using ngModel Directive

The angular framework provides one directive called the ngModel directive to simplify two-way data binding. You can modify existing code using the ngModel directive, as shown below.

You can see the above error due to we need to add the FormsModule in app.module.ts file

imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],

Then finally using below code we ca see it work the two-way data binding using ngModel.

  <input [(ngModel)]='name'>
  You entered : {{name}}

Custom Two-way binding

As we mentioned earlier the [()] to work, we need to have a property with the change event as Change.

We do not have any HTML Elements which follows the above naming conventions, but we can create a custom component

<button (click)="increment()">Increment</button>
Count: {{ count }}
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
 
  @Input() count: number = 0;
  @Output() countChange: EventEmitter<number> = new EventEmitter<number>();
 
  increment() {
   this.count++;
   this.countChange.emit(this.count);
 }
}

The component has two properties one is input property count decorated with @Input(). The other in is an event (or output property), which we decorate with @Output(). We name the input property as count. Hence the output property becomes countChange.

Conclusion

The two-way binding is a simple, but yet powerful mechanism. We use Property binding & Event binding to achieve the two-way binding. Angular does have a [(value)] syntax to which sets up the two-way binding.

Leave behind your valuable queries and suggestions in the comment section below. Also, if you think this article helps you, do not forget to share this with your developer community. Happy Coding 🙂

Jayant Tripathy
Coder, Blogger, YouTuber

A passionate developer keep focus on learning and working on new technology.

Leave a Reply

Your email address will not be published.