Two Data Binding
Written By: Avinash Malhotra
Updated on
Two Way Data Binding is the technique where the model and view and interconnected. Any change in model or view can synchronize data between both. Angular supports both One way Data binding and Two Way Data Binding.
For example when we are typing, the input data will update from view (template) to model (class) and will print in next tag at same time. All this happens very fast.
Two Way data binding techniques in angular
- without ngModel
- with ngModel
Example
$event
Two Way Data binding without ngModel is possible by using event and property binding. $event object return event itself.
$event without function
<!-- app.component.ts -->
export class AppComponent {
name = '';
}
<!-- app.component.html -->
<input type="search" (input)="name=$any($event.target).value">
<output>{{name}}</output>
$event with function
<!-- app.component.ts -->
export class AppComponent {
name = '';
updateName(x:Event){
//this.name=x.target.value;
this.name=(x.target as HTMLInputElement).value;
};
}
<!-- app.component.html -->
<input type="search" (input)="updateName($event)">
<output>{{name}}</output>
ngModel
Two way data binding with ngModel is possible by combining both Property Binding and Event Binding. For Property binding, we use [], for event binding we use (). For two way data binding using ngModel, we use ([]).
Two Way Data Binding
[]
Property Binding
()
Event Binding
=
[()]
Two-Way Data Binding
For standalone, import FormsModule in app.component.ts and add FormsModule in imports in component decorator.
import FormsModule
<!-- app.component.ts -->
import { Component } from '@angular/core';
import {FormsModule} from "@angular/forms";
@Component({
selector: 'app-root',
imports: [ FormsModule],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'ngApp';
name="";
}
import in modules
(For angular non standalone application)
For Angular non standalone, to use ngModel, first import FormsModule in app.module.ts. After importing FormsModule, declare FormsModule in imports in @NgModule.
<!-- app.module.ts -->
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
use ngModel
<!-- app.component.html -->
<input type="text" [(ngModel)]="name">
<!-- app.component.ts -->
export class AppComponent {
name = '';
}