Angular2 two-way data binding

Ronald Wildenberg picture Ronald Wildenberg · May 26, 2015 · Viewed 60.5k times · Source

I know Angular2 doesn't have two-way data binding but is there a way to mimick the two-way data binding behavior from Angular1.x?

Answer

PSL picture PSL · May 27, 2015

Note - scroll down the answer for ng-model binding

You could actually do that, just that you need to invoke internal changelistener tick (similar to digest) to update binding in the zone, You can just add a (keyup) event for that. Similarly you could use directive bindings as well with properties dictionary of component settings.

Example:-

<input #label (keyup)> 
<!-- variable #label represented as the element itself and accessible as property on controller instance 
 You can even bind keyup to a function or another another function and pass value from the label property-->

Display as:

<p>{{label.value}}</P>

Parent Component has a textbox and a label.

import { Component, bootstrap} from '@angular/core';
import {Display} from 'display';

@Component({
  selector: 'my-app',
  template: `<p><b>Parent Component:</b><p><input #label (keyup) (change)="handleChange(label.value)">
        <p>{{label.value}}</P> <display [text]="label"></display></p></p>`,
  directives: [Display]
})

class MainComponent {
  label: any;

  constructor() {

  }

  handleChange(label){
    this.label = label;
    console.log(this.label);
  }

}

Now displaying it in child component as well:

@Component({
  selector: 'edit',
  template: `<p><b>Child Component:</b></p>{{text.value}}`
})

export class Edit {
    @Input() text:any;
}

Demo



Update - ng-model for 2-way binding

Though Angular2 is one-time bound by default, ngModel sugar has been introduced to achieve 2-way binding. With that you could do for instance:

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

Here usage of square brackets ([..]) suggests the property binding and round brackets ((..)) for event binding. Basically when you use ng-model, you are enabling both the bindings ngModel is more of an event. Behind the scenes it creates an observable event(with EventEmitter) to track the value changes in the bound element and update the bound property respectively. For example:-

Include formDirectives:

 import {FORM_DIRECTIVES} from '@angular/common';

and with form

   <form (ngSubmit)="onSubmit()" let-f="form">
      <input ngControl="name" [(ngModel)]="name">
      <button>Click me and check console</button>
   </form>

without form

  <input  [(ngModel)]="name">
  <button (click)="onSubmit()">Click me and check console</button>

not necessary anymore include formDirectives dependency in view annotation.

@Component({
  template: .....,
  directives: [FORM_DIRECTIVES]
})

Demo

Also read the nice write up from Victor Savkin on Two-way binding in angular2 by creating the ng-model event and how it works.