データバインディングはコンポーネントのクラスとそのテンプレートを接続します。Angularには4つの形式があり、データフローの方向と独特の構文によって区別されます。
1. Interpolation — クラス → ビュー(テキスト)
html
{{ title }}
{{ price * quantity }}
<img [src]="imageUrl" /> <!-- bind a DOM property -->
<button [disabled]="isLoading">Save</button>
<app-child [user]="currentUser"></app-child> <!-- pass to a component @Input -->
角括弧 [ ] はプロパティを式にバインドします(一方向で、データはビューに下に流れます)。
<button (click)="save()">Save</button> <!-- DOM event → method -->
<input (input)="onInput($event)" /> <!-- $event = the event object -->
<app-child (deleted)="onDeleted($event)"></app-child> <!-- component @Output -->
丸括弧 ( ) はイベントをリッスンします(一方向で、データはビューからクラスに上に流れます)。
<input [(ngModel)]="name" /> <!-- the "banana in a box" [()] -->
<p>{{ name }}</p> <!-- stays in sync as you type -->
[(...)] 構文(「箱の中のバナナ」)はproperty bindingとevent bindingを組み合わせて双方向同期を行います — 最も一般的にはフォーム入力の ngModel で使用されます。
{{ }} → interpolation (class → view, text)
[ ] → property (class → view)
( ) → event (view → class)
[( )] → two-way (both) — it's literally [ ] + ( )
双方向の [()] は単にproperty binding [] とevent binding () を組み合わせたものです — 括弧は方向を示しています。
データバインディングはAngularがクラスとテンプレートを同期させ続ける方法です — すべての動的UIの背後にあるメカニズムです。
4つの種類とそれぞれの構文({{}}、[]、()、[()])、およびそれぞれがどの方向に流れるかを知ることは、Angularテンプレートを読み書きするのに不可欠です。Angularテンプレートのほぼすべての行はこの4つのうちの1つを使用しています。