0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Angular データバインディングについて

Posted at

はじめに

コンポーネントは以下の図のように、ビューを定義し制御するものということを以前解説した。(リンク:Angular コンポーネントとは)
図.png
コンポーネントとビューについて理解してから、データバインディングについて学習することをオススメしたい。
今回はコンポーネントとビュー間でデータをやり取りする仕組みであるデータバインディングについて解説する。

データバインディングの種類

データバインディングは以下の図のように3方向のデータの受け渡しが可能
image.png

それぞれのバインディング方法について簡単に説明したい。

補間・プロパティ・属性バインディング

コンポーネントのデータをテンプレート(HTML)に反映させる方法には、補間(インターポレーション)、プロパティバインディング、属性バインディングがある。

補間(インターポレーション)

{{ }} を使って、コンポーネントのプロパティをHTML内に埋め込む方法。

sample1.html
<p>{{ message }}</p>
sample1.ts
export class AppComponent {
  message = 'Hello、Angular!';
}

この場合、message の値が <p> 内に表示される。

プロパティバインディング

[property]=" "で、input 要素の [value] 属性に、コンポーネントの message プロパティをバインドします。

sample2.html
<p><input [value]="message"></p>
sample2.ts
export class AppComponent {
  message = 'Hello、Angular!';
}

入力欄の初期値がmessageからHello、Angular!に変更される。

属性バインディング

HTMLの属性にコンポーネントのデータを適用する場合は、attr. プレフィックスを使用する。

sample3.html
<td [attr.colspan]="columnSpan">セル結合</td>
sample3.ts
export class AppComponent {
  columnSpan = 2;
}

この場合、colspan="2" が動的に設定される。

プロパティバインディングと属性バインディングの違いは以下の通り。

項目 プロパティバインディング [property] 属性バインディング [attr.attribute]
適用対象 DOM要素のプロパティ HTMLの属性
リアルタイム反映 可能(データ変更で即座に反映) 初回レンダリング時のみ
動的な動作への影響 あり(フォームの入力値など) なし(単なる属性の設定)
主な用途 value, disabled, checked など colspan, aria-label など

イベントバインディング

ユーザーの操作(クリック、キー入力など)に応じてコンポーネントのメソッドを実行する方法。

sample4.html
<button (click)="onClick()">クリック</button>
<p>{{ message }}</p>
sample4.ts
export class AppComponent {
  message = 'ボタンをクリックしてください';

  onClick() {
    this.message = 'クリックされました!';
  }
}

ボタンをクリックすると onClick() メソッドが実行され、message の値が更新される。

双方向バインディング

[(ngModel)] を使うことで、入力値とコンポーネントのデータを同期させる。

sample5.html
<input [(ngModel)]="message" />
<p>{{ message }}</p>
sample5.ts
export class AppComponent {
  message = '初期メッセージ';
}

この場合、input に入力した内容がリアルタイムで message に反映される。

まとめ

データバインディングには、補間・プロパティ・属性バインディング、イベントバインディング、双方向バインディングの3方向のバインディング方法がある。補間やプロパティバインディングはコンポーネントのデータをテンプレート(ビュー)に反映させるのに対し、イベントバインディングはユーザーの操作をコンポーネントで処理する。双方向バインディングでは、コンポーネントとビューのデータが常に同期される。
今回はデータバインディングの概要について簡単に説明した。細かい内容はまた今度解説したい。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?