← 解説「テンプレート参照変数 — # で要素に名前を付ける」に戻る
サンプルコードで身につける: テンプレート参照変数 — # で要素に名前を付ける
解説で学んだ概念を、5つの具体例で確認します。素朴な例から実務寄りの例へと進みます。
1ボタンを押した瞬間の入力値を渡す
テンプレート参照変数の最も基本的な使い方です。#nameEl で input に名前を付け、クリック時に nameEl.value をメソッドへ渡します。値を常に追跡する必要がないなら、ngModel を使うよりこちらが手軽です。
import { Component } from '@angular/core';
@Component({
selector: 'app-guest-form',
// #nameEl と名前を付け、同じテンプレート内で参照する
template:
'<input #nameEl placeholder="お名前">' +
'<button (click)="register(nameEl.value)">登録</button>',
})
export class GuestFormComponent {
register(name: string) {
console.log(name + 'さんを登録しました');
}
}
2別の要素へフォーカスを移す
参照変数はDOM要素そのものなので、focus() のようなメソッドをテンプレートから直接呼べます。「検索を開くボタンを押したら入力欄にカーソルを入れる」といったフォーカス制御が、クラス側のコードなしで書けます。
import { Component } from '@angular/core';
@Component({
selector: 'app-quick-search',
// クリックで #searchEl の focus() をテンプレートから直接呼ぶ
template:
'<button (click)="searchEl.focus()">検索をはじめる</button>' +
'<input #searchEl placeholder="キーワード">',
})
export class QuickSearchComponent {}
3入力のたびに文字数を数える
参照変数と (input) イベントを組み合わせ、打つたびに現在の値をメソッドへ渡す例です。入力欄の「今の状態」を必要な瞬間だけ読み取る、参照変数らしい使い方です。
import { Component } from '@angular/core';
@Component({
selector: 'app-char-counter',
// 入力イベントのたびに msgEl.value を読み取って渡す
template:
'<textarea #msgEl (input)="updateCount(msgEl.value)"></textarea>' +
'<p>{{ count }} 文字入力中</p>',
})
export class CharCounterComponent {
count = 0;
updateCount(text: string) {
this.count = text.length;
}
}
4子コンポーネントのメソッドを呼ぶ
参照変数をコンポーネントのタグに付けると、DOM要素ではなくそのコンポーネントのインスタンスが手に入ります。親のテンプレートから子のpublicメソッドを直接呼べるので、再生・停止のような操作の指示に使えます。
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-video-player',
template: '<p>状態: {{ playing() ? "再生中" : "停止中" }}</p>',
})
export class VideoPlayerComponent {
playing = signal(false);
play() { this.playing.set(true); }
stop() { this.playing.set(false); }
}
@Component({
selector: 'app-theater',
imports: [VideoPlayerComponent],
// #player はコンポーネントのインスタンスを指す
template:
'<app-video-player #player />' +
'<button (click)="player.play()">再生</button>' +
'<button (click)="player.stop()">停止</button>',
})
export class TheaterComponent {}
5チェック状態でボタンを制御する
checkbox の参照変数から checked プロパティを読み、そのままボタンの [disabled] に使う例です。1回きりの確認のような小さなUIなら、クラスにプロパティを持たせなくても参照変数だけで完結できます。
import { Component } from '@angular/core';
@Component({
selector: 'app-delete-confirm',
// agreeEl.checked をそのまま [disabled] の条件に使う
template:
'<label>' +
' <input type="checkbox" #agreeEl> 削除してよいことを確認しました' +
'</label>' +
'<button [disabled]="!agreeEl.checked" (click)="remove()">削除する</button>',
})
export class DeleteConfirmComponent {
remove() {
console.log('削除を実行しました');
}
}