Angular Two Way Data Binding

Angular Two way data binding is a combination of event binding and property binding. Suppose, you want to exchange data from component to view or view to component then we use Angular Two way binding.

ngModel Directive

ngModel Directive is used to bind the Two way data binding on HTML Form elements. It binds to a form element like input, select, etc.

Syntax:-


[(ngModel)]="value"

ngModel is a part of Forms Module library so you need to import the FormsModule package into your Angular module.


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

There are some steps to implement two way data binding.

Step1) include FormsModule package into the app-module.ts file


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

Step2) create userName variable which is string datatype into the app-component.ts file


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  userName : string ='';
}

Step3) create input field which has ngModel directive which has value userName in app-component.html file


<div class="container" align="center" style="margin-top: 20px;">
    <input type="text" name="uname" [(ngModel)]="userName" />
    <br/>
    <h3>Hello {{userName}}</h3>
  </div>

Step4) Now open the localhost URL


http://localhost:4200/

Step5) Now, fill the name then get the value.