One of the major features of angular is two-way data binding in components. But, Angular also focuses on splitting the work into smaller components. Now there can be situations where you have split your task into the smaller components but then you come up with another requirement that you also want two-way data binding between your components. How you will achieve it. In this article, we will look at the same concept of two-way data binding between your two components from scratch.

What is two-way data binding

Two-way data binding can be achieved using a ngModel directive in Angular. The below syntax shows the data binding using (ngModel), which is the combination of both the square brackets of property binding and parentheses of the event binding.

<input type="text" [(ngModel)] = 'val' />

Before using ngModel to achieve two-way data binding, it’s very important to import the FormsModule from @angular/forms in the app.module.ts file as shown below. FormsModule will contain the ngModule directive.

Filename app.module.ts

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { FormsModule } from "@angular/forms"; 
 import { AppComponent } from './app.component'; 
import { FormsModule } from "@angular/forms";
 @NgModule({ 
   imports: [BrowserModule, FormsModule], 
   declarations: [ AppComponent], 
   bootstrap: [AppComponent] 
}) 
export class AppModule { }

If you do not import the FormsModule, then you will get Template parse errors and it will result in this error:

“Can’t bind to ‘ngModel’ since it is not a known property of ‘input’”.

After importing the FormsModule, you can go ahead and bind data using (ngModel) as shown below.

Filename app.component.ts

import { Component } from '@angular/core'; 
 @Component({ 
   selector: 'app-example', 
   template: ` 
               Enter the value  : <input [(ngModel)] ='val'> 
               <br> 
                Entered value is:  {{val}} 
             ` 
}) 
export class AppComponent { 
   val: string = ''; 
}

Image for post

#javascript #front-end-development #typescript #angularjs #angular

How to Use Two-Way Data Binding Between Components
1.50 GEEK