← 解説「@switch — 値ごとに表示を分ける」に戻る
サンプルコードで身につける: @switch — 値ごとに表示を分ける
解説で学んだ概念を、5つの具体例で確認します。素朴な例から実務寄りの例へと進みます。
1値に一致したものだけ表示する
@switch の最小例で、color の値に一致した @case だけが描画されます。@if の条件式と違い「1つの値が何か」だけを見ているのがポイントです。信号のように取りうる値が決まっているデータの表示分けに向いています。
import { Component } from '@angular/core';
@Component({
selector: 'app-traffic-light',
// color の値に一致した @case だけが描画される
template:
'@switch (color) {' +
' @case ("red") { <p>止まれ</p> }' +
' @case ("green") { <p>進め</p> }' +
'}',
})
export class TrafficLightComponent {
color = 'red';
}
2@default で「それ以外」を受け止める
どの @case にも一致しなかったときの表示は @default に書きます。想定外の値が来ても画面が空白にならない、という安全網の役割です。ユーザー権限のように将来値が増えるかもしれないデータでは、@default を必ず用意しておくのが実務の作法です。
import { Component } from '@angular/core';
@Component({
selector: 'app-role-label',
// どの @case にも一致しなければ @default が描画される
template:
'@switch (role) {' +
' @case ("admin") { <p>管理者</p> }' +
' @case ("editor") { <p>編集者</p> }' +
' @default { <p>閲覧者</p> }' +
'}',
})
export class RoleLabelComponent {
role = 'editor';
}
3数値で分岐する
一致判定は === で行われるため、数値のプロパティには数値の @case を書きます。@case ("6") と文字列で書いてしまうと一致しない、という型の落とし穴を学べる例です。曜日番号やステータスコードなど、数値で種類を表すデータでよく使います。
import { Component } from '@angular/core';
@Component({
selector: 'app-weekday-label',
// 一致判定は === なので、数値の値には数値の @case を書く
template:
'@switch (dayOfWeek) {' +
' @case (0) { <p>日曜日</p> }' +
' @case (6) { <p>土曜日</p> }' +
' @default { <p>平日</p> }' +
'}',
})
export class WeekdayLabelComponent {
dayOfWeek = 6;
}
4注文ステータスをユニオン型で表示分けする
取りうる値をユニオン型で宣言しておくと、@switch との相性が抜群です。値の種類がコード上で明示されるため、分岐の漏れに気づきやすくなります。注文・配送・支払いなど、業務システムの「ステータス表示」はほぼこの組み合わせで書かれます。
import { Component } from '@angular/core';
// 取りうる値を型で先に決めておく
type OrderStatus = 'pending' | 'shipped' | 'delivered';
@Component({
selector: 'app-order-status',
template:
'@switch (orderStatus) {' +
' @case ("pending") { <p>発送準備中</p> }' +
' @case ("shipped") { <p>配送中</p> }' +
' @case ("delivered") { <p>お届け済み</p> }' +
'}',
})
export class OrderStatusComponent {
orderStatus: OrderStatus = 'shipped';
}
5通知一覧を種類ごとに描き分ける
@for で通知を繰り返しつつ、各行の中で @switch により種類ごとの見せ方を変える実務寄りの例です。制御フロー構文は入れ子にして組み合わせられることを示しています。通知センターやアクティビティフィードはまさにこの構造です。
import { Component } from '@angular/core';
type Notice = { id: number; kind: 'info' | 'warn' | 'error'; text: string };
@Component({
selector: 'app-notice-list',
// @for の中に @switch を入れ子にできる
template:
'@for (notice of notices; track notice.id) {' +
' @switch (notice.kind) {' +
' @case ("warn") { <p>【警告】{{ notice.text }}</p> }' +
' @case ("error") { <p>【エラー】{{ notice.text }}</p> }' +
' @default { <p>{{ notice.text }}</p> }' +
' }' +
'}',
})
export class NoticeListComponent {
notices: Notice[] = [
{ id: 1, kind: 'info', text: '新機能を公開しました' },
{ id: 2, kind: 'error', text: '保存に失敗しました' },
];
}