Introduction

Two-way binding can be used when values in an element are being updated constantly and when there is a need to listen for events on that element. Two way-binding is a combination of both the square brackets like those used in property binding and round brackets that are used in event binding [()].

Example

Using two-way binding with forms

  1. Open the app.modules.ts file and import FormsModule:

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

  1. In the imports array, type FormsModule.

Your file should look like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
]

Now, in your AppComponent class in app.component.ts create a message variable:

public message: string = '';

In the template for AppComponent, insert the following:

<input [(ngModel)]="message"/>
<p>{{message}}</p>

Save the files and run your application by typing in the terminal in Angular project’s directory: npm start or yarn start.

You should now see that whenever you type anything in the input field, it automatically appears. That is two-way binding.

The example we did above is equivalent to the following:

<input [value]="message">
(input)="message=$event.target.value">
{{message}}

Or in shorthand form:

<input [ngModel]="message"
(ngModelChange)="message=$event">
{{message}}

NgModel sets the value of message to whatever the user types and ngModelChange keeps track of any changes to the value of message by listening.

NOTE: [(ngModel)] can only assign a value to a property. It cannot manipulate it. In order to do that, we would use [ngModel] and (ngModelChange).