×
☰ See All Chapters

Angular Two Way Binding

Two way binding means that changes made in the component data are propagated to the view and that any changes made in the view are immediately updated in the underlying component data. Two-way binding is used mainly in data entry forms. Whenever user makes changes in the data, we would like to update our model in the component with the new data and if the model changes, we would like to update the view as well. The Angular uses the combination of Property binding (from component to view) and event binding (from view to component) to achieve the Two-way data binding. This is done so by using the ngModel directive.

<input [(ngModel)] =’name’></input>

 

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 indicate the event binding.

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 as shown below.

import { BrowserModule } from '@angular/platform-browser';

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

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

 

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

 

@NgModule({

        declarations: [

                AppComponent

        ],

        imports: [

                BrowserModule, FormsModule

        ],

        providers: [],

        bootstrap: [AppComponent]

})

export class AppModule { }

Angular Two Way Binding Example

app.component.ts

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

 

@Component({

  selector: 'app-tag',

  template: `Enter your Name : <input type='text' [(ngModel)]='name' />

                        You have entered {{name}}`,

})

export class AppComponent {

  name: string='';

}

 

app.module.ts

import { BrowserModule } from '@angular/platform-browser';

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

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

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

 

@NgModule({

        declarations: [

                AppComponent

        ],

        imports: [

                BrowserModule, FormsModule

        ],

        providers: [],

        bootstrap: [AppComponent]

})

export class AppModule { }

index.html

<!doctype html>

<html lang="en">

<head>

  <meta charset="utf-8">

  <title>Angular Example</title>

  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="icon" type="image/x-icon" href="favicon.ico">

</head>

<body>

  <app-tag></app-tag>

</body>

</html>

Output

angular-two-way-binding-0
 

All Chapters
Author