ng-model in Angular2 (two-way data binding)

One of the things that made me love Angular 1.x was how easy it is to use two-way data binding. Luckily it's also a breeze to use in Angular2!

What is two-way data binding?

To simply put it, two-way data binding is keeping the model and the view synchronised. This means that when you change something in your view (e.g. by typing in an <input type="text" />) it should update your model, when you change your model (e.g. by calling a function) it should update your view respectively.

Creating the project

We're going to use the latest Angular2 version using the Angular cli. Install it with (sudo) npm i angular-cli -g or if you have installed it already but you're not sure if you have the latest version you can run (sudo) npm update angular-cli -g.

We're going to create a small case-switcher app. I believe this shows two-way data binding quite well. We update the model from an <input /> element and then modify it by calling a function that modifies the model onclick.

The Angular 1.x way

Just like in my previous example, I went ahead and created our desired application in Angular 1.2.

In this example we bind the (ng-)model username to the controller. When you type it shows what you're typing next to the input box. Now when you call toLowerCase() or toUpperCase() it updates the model and automatically updates the view (yaay two-way data binding!).

The Angular2 way

The HTML is really simple. It took a while to get used to Angular2's new syntax (event) and [property] (which I discuss briefly in this post) but now it just feels more natural than the "old way".

  <input type="text" [(ngModel)]="username" />
  <button (click)="toUpperCase()">UPPERCASE!</button>
  <button (click)="toLowerCase()">lowercase!</button>

  <h1>{{ username }}</h1>

As explained in my previous post, the (click) just stands for an event. However this [(ngModel)] is new. This means two-way data binding. Whereas [property] just writes into a property (one-way data binding).

The JavaScript (well TypeScript) is really simple as well.

export class CaseSwitcherApp {  
  username: string;

  toUpperCase () {
    this.username = this.username.toUpperCase();
  toLowerCase () {
    this.username = this.username.toLowerCase();

That's how easy it is really, not vastly different from Angular 1.x.

TypeScript is cool

To play around with it I changed the toUpperCase() function to:

toUpperCase () {  
    this.username = parseInt(this.username, 10);

It wouldn't even run and the TypeScript compiler immediately threw this error at me,.

I feel like this is an extremely helpful tool that can save you from a lot of mistakes, especially with large applications.


This was the third post into my "Angular 1.x built in directives in Angular 2.0" series. I like to keep the posts small and simple with a little bit of useful information in each of them.

If you liked it don't hesitate to message me on Twitter @Jilles.