How to Use Two-Way Data Binding Between Components

Mehul Kothari
The Startup
Published in
6 min readSep 5, 2020

GitHub link:https://github.com/mehulk05/Two-way-data-binding-between-components

Live Url:https://mehulk05.github.io/Two-way-data-binding-between-components/

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 = '';
}

Two way-data bindings between two components

Before we begin let's have a little overview about the project we are going to build

Overview

In the project, we are going to have two-part i.e left-form and right-form

The left form has 4 input fields. All input fields are associated with their input symbols. When the value if filled and clicked enter, the value will be reflected in the right form with the respective symbol.

When the symbol is entered in the right form and some value is entered that value should be reflected in the left form immediately on every click event. Also, we have a clear button in the right form so when we click on it all the input value should be cleared in both the forms.

So let’s begin by creating a brand new project and then creating two components and service to create two-way data binding between our components

Step1: Create a new Angular project

ng new Two-way-binding
cd Two-way-binding
ng serve

Step 2: Create two components and service

ng g c left-form
ng g c right-form
ng g s shared/shared
ng g s shared/labeldata
ng g s shared/symboldata

In the above command, ng is an angular provided module. g stands for generate , c stands for component and left-form is the component name. Similarly, ng g s shared/shared where g stands for generate ,s stands for service.

Step 3: Creating 4 fields in the left-form component.

left-form.html

In the above code, we are not hard coding symbols and label instead we are getting those data from service i.e symbol data service and label data .service.Also, we have ngModel on the input field and passing a key event i.e when the user hits the enter button some action should be taken on the handleInput_On_Enter() function.

left-form.component.ts

In the code, we are handling click events and passing the method to service with some arguments. Now here in the above code ignore the code in ngOnInit which we don't need right now.

left-form component

Step 4: Creating the Right Form Component

Now here basically what we will do is as shown at the top in the demo example that whenever I enter some value in the left form and hit enter, it should get reflected in the right string with its appropriate symbol. Also when I enter any value in the right form with its appropriate symbol we should see value in the left-form field directly updating.

right-form.component.html

So in the above code, all we have is one input field on which we have ngModel and ngmodelChange event bind with some function. So let's see in the next code what we are doing with that function. Also, we have clear all button to clear all values on the right side of the form and left side of the form.

Right-form.component.ts

So in this code again ignore the code in ngOnInit.After that, we have two functions two clear all and handle input when model change where we are calling our service. So let's jump to our service code where our whole logic lies.

right form component

Step 5: Creating our shared Service

Shared service is the service where logic will be shared across both the component. Also, it handles the function calls from both the component.

Shared.service.ts

So let's go one by one with all the functions in shared service. We have two subjects at the top which we are going to send to our components when will pass some value to it. Next, we have two function

1- SetInputString() ,SetSearchString()

When we want to pass some value to our subject we will use our respective set Methods.

2. parseSearchString()

In the right-form method, we are calling this method with the input string. In this method, we will get a complete string as an argument. Now we need to parse it and find the symbol. For the matching symbol, we need to assign it to the SetInput method where we are setting our set input subject. In the left form component in the ngOnInit method, we will subscribe and get the data for our respective label with live updating in input fields on both ends

for eg String =/ABC #123 we get from the right-form component

and symbol for the first name =/

the symbol for phone no = #

then we will parse the string and send the value ABC to our left form component and assign it to the first name similarly parse the # part and send it to our left -form component and assign it to phone no

3 appendSymbol()

From the left-form component, we get 4 arguments and we pass this argument to the append symbol method where need to append a specific symbol to our specific value.

For eg: / symbol for first name

# for phone no

We will append symbol and pass this value to set the search string method where we will pass the value to our subject and in the right-form component, we will subscribe to our value and display it in the input field.

4 ClearAll()

When we click on clear all from the right-form component the all input value in both the component should be cleared. So we call the method from service clear all the values and pass it to our Set methods where we set our subjects. Thereafter in ngOnInit, we subscribe to our subject and fetch the latest updated value.

Step 6: Symboldata.service.ts

Step 7: LabelData.service.ts

two-way data binding between two components

Conclusion

So here we are done with our two-way data binding between our components which becomes very crucial in our day to day role if we are working in frontend development with our small pieces of components.

If you find any doubt feel free to reach me in the comments or on GitHub.

--

--

Mehul Kothari
The Startup

Mean stack and Full stack Developer. Open to work as freelancer for designing and developing websites.