Two-way data binding in Angular using ngModel directive

by Sai gowtham1min read
Two-way data binding in Angular using ngModel directive

In this tutorial, we are going to learn about angular two-way data binding using the ngModel directive.

What is Two-way data binding?

Two-way data binding means data flows in both directions, The data in view changes it also updates the model, The data in the model changes it also updates the view.

ngModel directive

Angular provides us a ngModel directive by using that we can sync the data in both directions.


To use a ngModel directive inside our components first we need to import the FormsModule in app.module.ts file and add it to the imports array.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

  declarations: [
  imports: [
    FormsModule  ],
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Let’s use the ngModel model directive.

import { Component } from '@angular/core';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']

export class AppComponent {
  myname = 'Angular';}
    <input [(ngModel)]="myname" />    <h1>{{myname}}</h1>

In the above code ,we have added [(ngModel)]= "myname" it means we are binding input element in both directions to myname property.


Have you seen in the above image, two-way data binding is working successfully.