angular 4 two way data binding sample

Posted on February 8, 2018 by Suresh Kamrushi in Javascript

Here I showing how you can bind data using Angular 4. This is very simple can be done within no time.
Let see how we can do that.
Hope you have to install angular in your system if you need help installing/configuring Angular you can refer to my blog “Here“.
Now to start with, First open the command prompt and navigate to the directory where your want to start with and create a new Angular project as below:

 > ng new twoWayBinding

Above command create a project with “twoWayBinding” in directory space. it will take sever minutes to complete.
Once it is completed you get a message like “Project ‘twoWayBinding’ successfully created.”.
Now change directory to “twoWayBinding” folder and type below command to initiate the project:

 > ng serve

you will get message like “webpack: Compiled successfully.”
Now open the browser and hit the url “http://localhost:4200/” you can see the welcome page from angular.

Now you have to make changes in your “app.modules.ts” and “app.component.html” files located in “twoWayBinding\src\app”.
1. Update “app.modules.ts” file as below:
Add forms module at the top like below:

import { FormsModule } from '@angular/forms';

And add “FormsModule” in imports inside “@NgModule”.
2. Update your HTML as below:
Open “app.component.html” file and add below code:

< input [(ngModel)]=”username”>
<div>two – way binding Example: {{username}}</div>
Now open the url “http://localhost:4200/” browser and start typing in text box, it wil reflact immediately on div.
Hope it will help someone!!!!

  Comments or questions are welcome