What is two-way data binding in Angular

Through two-way data binding, Angular doesn’t just look at the variables for changes. It also keeps track of user modifications (e.g. with input-elements) and updates the variables accordingly.

Therefore the variables in the code always represent what appears in the view!

Two-way angular data binding is actually quite rare. But there is one commonly used directive which allows data binding in two ways. This directive is known as ngModel.

ngModel is a member of the Angular “FormsModule”, and must be manually imported into your module.

import { NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormsModule } from '@angular/forms'

import { AppComponent } from './app.component'

@NgModule({
  imports: [BrowserModule, FormsModule],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
})
export class AppModule {}

ngModel can be used for the implementation of two-way data binding with form-elements such as inputs. To do this, we need to use a quite different syntax: [(ngModel)]. It’s a one-way syntax mix with the event binding syntax.

Used like this:

<input [(ngModel)]="name" />

Don’t miss these tips!

We don’t spam! Read our privacy policy for more info.

Open chat
Powered by