Two-way Data Binding Angular 8

Any change in the template (view) in one-way data binding was not reflected in the component. The two-way binding, however, facilitates to update data from component to view and from view to the component. The automatic synchronization of data happens in Two Way Data Binding between the Model and the View. It means that changes made in the Model will be reflected in the View and the changes made in View will be reflected in Model. To secure that the HTML template and the TypeScript code are updated at each time, the changes made will be reflected in both components immediately and automatically. Both the property binding and event binding are combined in two-way data binding.

Syntax:

[(ngModel)] = "[property of the component]"

The ngModel directive needs to be enabled for two-way data binding. The FormsModule needs to be added in imports[] array in the AppModule, because the ngModel directive depends upon FormsModule in angular/forms package.

Example:

  • Open the project’s app.module.ts file.
  • Add the following code to it.

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 { }

  • Open app.component.ts file.
  • Add the below code in it.

app.component.ts:

import { Component } from "@angular/core";    
@Component({    
  selector: "app-root",    
  templateUrl: "./app.component.html",    
  styleUrls: ["./app.component.css"]    
})    
export class AppComponent {    
  fullName: string = "Hello World";    
}

  • Open app.component.html.
  • Add the below code to it.

app.component.html:

<h2>Two-way Binding</h2>    
   <input [(ngModel)]="fullName" /> <br/><br/>    
<p> {{fullName}} </p>

  • Run the ng serve command.
  • Open the localhost to view the output.

Output 1:

  • Change the textbox value and check the property value in the component. It will be updated too.

Output 2:

Please Share