Angular Two-way Data Binding

As you’ve learned the property binding and event binding, now we’re good to go with two-way data binding.

What Is Two-Way Data Binding in Angular?

The main disadvantage of one-way data binding is that it doesn’t get reflected in the TypeScript code when we make any change in the view. As a solution to this problem, Angular provides two-way data binding.

For example, when working with Form’s Module, the View and Class must always be in sync. Hence two-way data binding allows us to update the property and at the same time to display it as well. For two-way data binding Angular provides a cool directive called ngModel directive.

Syntax of ngModel

[(ngModel)] = "property_name"

NOTE: To use ngModel, we’ve to import FormsModule from @angular/forms in the app-routing.module.ts file and export it.

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import {FormsModule} from '@angular/forms'

const routes: Routes = [];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule,FormsModule]
})

export class AppRoutingModule { }

Example

Now let’s see how two-way data binding works in Angular.

Step 1: Let’s take an input field where we’ll be entering some text.

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

Step 2: Let’s create an empty property called input in the TypeScript file to store the input data.

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html', 
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'my-app';
  input = ""
}

Step 3: Now, let’s enter some data and display it in the View using Interpolation.

<h3>{{input}}</h3>

Output:

two way data binding in angular example

Here the Class and View are in sync. This is because the data we’re giving to the input field is also displayed simultaneously. Hence two-way data binding occurring.

Conclusion

Naturally, we use ngModule when we’re working with Angular Forms. However, we’ll be learning Angular Reactive Forms in detail in a different module where you’ll see more use of ngModel.

We hope this article was well enough to clear your concepts on two-way data binding in Angular. In the upcoming articles, you’ll learn some more directives in Angular.

Read Next: Angular ngFor Directive

Leave a Reply

Your email address will not be published. Required fields are marked *