The ngModel

The ngModel is a directive used to bind the data from domain model in component class to view. Domain model is nothing but a property in the component class.

Binding can be done in two different ways with ngModel directive.

How does ngModel work?

Creates a FormControl instance from a domain model and binds it to a form control element.

The FormControl instance will track the value, user interaction, and validation status of the control and keep the view synced with the model. If used within a parent form, the directive will also register itself with the form as a child control.

Source: copied from NgModel component source code

One-way binding:

If ngModel attribute is just wrapped around with square brackets (“[ngModel]”) then it is one-way binding. Meaning, the value of the domain model in the component is set to the value in the template.

Ex: <input type=”text” [ngModel]=”oneWayBinding” />

After you set up your angular project. Inside of app.component.ts, add a property in the component’s export and access it in any tag with [ngModel]=”” in the template.

one way binding demo in plunker

Two-way binding:

If ngModel is wrapped with [()] syntax, then it is two-way binding. Meaning, the value on the right side of [()] in the template (or html) will be synced back and forth when changes were applied to the value of domain model either in view or in the component.

Ex: <input type=”text” [(ngModel)]=”twoWayBinding” />

It’s two way binding between component and the view. Whatever updated in the components model will be displayed in the view and vice versa.

The syntax will be different for two-way binding. [(ngModel)]=””. This syntax is often termed as “Banana in the box” as it is a bit hard to remember the syntax for beginners like us. The parenthesis () wrapping ngModel is banana and the square brackets is a box.

two way binding demo in plunker

Notice the difference between one way and two way bindings

  • one-way binding: [ngModel]
  • two-way binding: [(ngModel)]

Thanks for reading !


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s