Using Two-Way Data Binding

Two-way data binding combines the input and output binding into a single notation using the ngModel directive.

  1. <input [(ngModel)]="name" >

What this is doing behind the scenes is equivalent to:

  1. <input [ngModel]="name" (ngModelChange)="name=$event">

To create your own component that supports two-way binding, you must define an @Output property to match an @Input, but suffix it with the Change. The code example below, inside class CounterComponent shows how to make property count support two-way binding.

app/counter.component.ts

  1. import { Component, Input, Output, EventEmitter } from '@angular/core';
  2. @Component({
  3. selector: 'rio-counter',
  4. templateUrl: 'app/counter.component.html'
  5. })
  6. export class CounterComponent {
  7. @Input() count = 0;
  8. @Output() countChange = EventEmitter<number>();
  9. increment() {
  10. this.count++;
  11. this.countChange.emit(this.count);
  12. }
  13. }

app/counter.component.html

  1. <div>
  2. <p>
  3. <ng-content></ng-content>
  4. Count: {{ count }} -
  5. <button (click)="increment()">Increment</button>
  6. </p>
  7. </div>

View Example

原文: https://angular-2-training-book.rangle.io/handout/components/app_structure/two_way_data_binding.html