Welcome Guest! (App Version 3.1)

websitnero logo name

2 Way Data Binding

Two Way Binding in Angular

2-Way Binding is very helpful in reducing code and keeping the updated value of data both in the view (.html) and logic (.ts). We use the 'banana in a box' or [()] symbol to represnet the 2-way binding. "ngModel" directive is used to help implement this feature.

Practical Example of "2 Way Data Binding"

Please follow the mentioned steps:

  1. Create a compennt named 'home'
  2. Add the home component in the app.component.html file removing all boilerplate code there.
  3. Create 1 object (person) and 1 string (someName) which we will use to demonstrate to show working of 2-way data binding.
  4. Don't forget to add Forms Module for 2 way binding (ngModel) in app.module.ts

home.component.html

<input type="text" [(ngModel)]="someName" />
<p>{{someName}}</p>

<hr/>

<input type="text" [(ngModel)]="person.firstName" />
<input type="text" [(ngModel)]="person.lastName" />
<input type="number" [(ngModel)]="person.age" />

<p>{{person.firstName}}, {{person.lastName}}, {{person.age}}</p>

home.component.ts

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  someName: String = "Peter Martin";

  person = {
    firstName: "Rosy",
    lastName: "Silvia",
    age: 29
  }

  constructor() { }

  ngOnInit() {
  }

}

app.module.ts

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

import { AppComponent } from './app.component';
import { HomeComponent } from './components/home/home.component';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. You'll get the following result:

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.