[Angular マスター] Day 4 - イベント処理で反応するアプリを作る
Angularのイベントバインディング、clickやinputの処理、$eventの使い方、簡単なカウンター実装を説明します。
[Angular マスター] Day 4 - イベント処理で反応するアプリを作る
イベントバインディングとは
イベントバインディングは、クリック、入力、キー操作などのユーザー操作に反応するための仕組みです。
Angularでは、(event)="handler()"の形でイベントとメソッドをつなぎます。
graph LR
A[ユーザー操作] --> B["(click)"]
B --> C[コンポーネントのメソッド]
C --> D[データ更新]
D --> E[画面更新]
クリックイベント
もっとも基本的な例はボタンのクリックです。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { Component } from '@angular/core';
@Component({
selector: 'app-counter',
standalone: true,
template: `
<h2>クリック数: {{ count }}</h2>
<button (click)="increment()">クリック</button>
`,
})
export class CounterComponent {
count = 0;
increment() {
this.count += 1;
}
}
ボタンを押すとincrement()が実行され、countが増え、画面も更新されます。
inputイベント
入力欄の値を受け取りたい場合は、inputイベントと$eventを使えます。
1
<input (input)="onInput($event)">
1
2
3
4
onInput(event: Event) {
const value = (event.target as HTMLInputElement).value;
this.message = value;
}
TypeScriptでは、event.targetの型を明示すると扱いやすくなります。
よく使うイベント
| イベント | 用途 |
|---|---|
click | ボタン、カード選択 |
input | 入力中の値を受け取る |
change | 選択や値の変更 |
keyup | キーボード入力 |
submit | フォーム送信 |
Day 4のゴール
今日のゴールは、ユーザーの操作をコンポーネントのメソッドにつなぎ、データを更新できるようになることです。
この投稿は投稿者によって CC BY 4.0 の下でライセンスされています。
