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.
Example
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';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule ],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Let’s use the ngModel
model directive.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
myname = 'Angular';}
<div>
<input [(ngModel)]="myname" /> <h1>{{myname}}</h1>
</div>
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.