Angular UI パターン
コア原則
- 古いUIを決して表示しない - 実際にローディング中の場合のみローディング状態を表示
- エラーを常に表示する - ユーザーは何かが失敗したことを知る必要がある
- 楽観的更新 - UIを瞬時に感じさせる
- プログレッシブディスクロージャー -
@deferを使ってコンテンツを利用可能になった時点で表示 - グレースフルデグラデーション - 部分的なデータであってもデータがないよりは良い
ローディング状態パターン
黄金律
表示するデータがない場合にのみローディングインジケーターを表示する。
@Component({
template: `
@if (error()) {
<app-error-state [error]="error()" (retry)="load()" />
} @else if (loading() && !items().length) {
<app-skeleton-list />
} @else if (!items().length) {
<app-empty-state message="アイテムが見つかりません" />
} @else {
<app-item-list [items]="items()" />
}
`,
})
export class ItemListComponent {
private store = inject(ItemStore);
items = this.store.items;
loading = this.store.loading;
error = this.store.error;
}
ローディング状態決定木
エラーはあるか?
→ はい: 再試行オプション付きのエラー状態を表示
→ いいえ: 続行
ローディング中かつデータがないか?
→ はい: ローディングインジケーター(スピナー/スケルトン)を表示
→ いいえ: 続行
データはあるか?
→ はい、アイテムあり: データを表示
→ はい、ただし空: 空状態を表示
→ いいえ: ローディングを表示(フォールバック)
スケルトン vs スピナー
| スケルトンを使用する場合 | スピナーを使用する場合 |
|---|---|
| 既知のコンテンツ形状 | 未知のコンテンツ形状 |
| リスト/カードレイアウト | モーダルアクション |
| 初期ページ読み込み | ボタン送信 |
| コンテンツプレースホルダー | インライン操作 |
制御フローパターン
@if/@else による条件付きレンダリング
@if (user(); as user) {
<span>ようこそ、{{ user.name }} さん</span>
} @else if (loading()) {
<app-spinner size="small" />
} @else {
<a routerLink="/login">サインイン</a>
}
@for と Track
@for (item of items(); track item.id) {
<app-item-card [item]="item" (delete)="remove(item.id)" />
} @empty {
<app-empty-state
icon="inbox"
message="まだアイテムがありません"
actionLabel="アイテムを作成"
(action)="create()"
/>
}
@defer によるプログレッシブローディング
<!-- クリティカルコンテンツは即座に読み込む -->
<app-header />
<app-hero-section />
<!-- 非クリティカルコンテンツは遅延読み込み -->
@defer (on viewport) {
<app-comments [postId]="postId()" />
} @placeholder {
<div class="h-32 bg-gray-100 animate-pulse"></div>
} @loading (minimum 200ms) {
<app-spinner />
} @error {
<app-error-state message="コメントの読み込みに失敗しました" />
}
エラーハンドリングパターン
エラーハンドリング階層
1. インラインエラー(フィールドレベル) → フォームバリデーションエラー
2. トースト通知 → 回復可能なエラー、ユーザーは再試行可能
3. エラーバナー → ページレベルのエラー、データは部分的に使用可能
4. 全画面エラー → 回復不可能、ユーザーのアクションが必要
エラーを常に表示する
重要: エラーを静かに飲み込まないこと。
// 正しい - エラーは常にユーザーに表示される
@Component({...})
export class CreateItemComponent {
private store = inject(ItemStore);
private toast = inject(ToastService);
async create(data: CreateItemDto) {
try {
await this.store.create(data);
this.toast.success('アイテムが作成されました');
this.router.navigate(['/items']);
} catch (error) {
console.error('createItem 失敗:', error);
this.toast.error('アイテムの作成に失敗しました。もう一度お試しください。');
}
}
}
// 間違い - エラーが静かにキャッチされている
async create(data: CreateItemDto) {
try {
await this.store.create(data);
} catch (error) {
console.error(error); // ユーザーには何も表示されない!
}
}
エラー状態コンポーネントパターン
@Component({
selector: "app-error-state",
standalone: true,
imports: [NgOptimizedImage],
template: `
<div class="error-state">
<img ngSrc="/assets/error-icon.svg" width="64" height="64" alt="" />
<h3>{{ title() }}</h3>
<p>{{ message() }}</p>
@if (retry.observed) {
<button (click)="retry.emit()" class="btn-primary">再試行</button>
}
</div>
`,
})
export class ErrorStateComponent {
title = input("問題が発生しました");
message = input("予期しないエラーが発生しました");
retry = output<void>();
}
ボタン状態パターン
ボタンのローディング状態
<button
(click)="handleSubmit()"
[disabled]="isSubmitting() || !form.valid"
class="btn-primary"
>
@if (isSubmitting()) {
<app-spinner size="small" class="mr-2" />
保存中... } @else { 変更を保存 }
</button>
操作中は無効化
重要: 非同期操作中は常にトリガーを無効化すること。
// 正しい - ローディング中はボタンが無効化される
@Component({
template: `
<button
[disabled]="saving()"
(click)="save()"
>
@if (saving()) {
<app-spinner size="sm" /> 保存中...
} @else {
保存
}
</button>
`
})
export class SaveButtonComponent {
saving = signal(false);
async save() {
this.saving.set(true);
try {
await this.service.save();
} finally {
this.saving.set(false);
}
}
}
// 間違い - ユーザーが複数回クリックできる
<button (click)="save()">
{{ saving() ? '保存中...' : '保存' }}
</button>
空状態
空状態の要件
すべてのリスト/コレクションには空状態が必須です:
@for (item of items(); track item.id) {
<app-item-card [item]="item" />
} @empty {
<app-empty-state
icon="folder-open"
title="まだアイテムがありません"
description="最初のアイテムを作成してください"
actionLabel="アイテムを作成"
(action)="openCreateDialog()"
/>
}
コンテキストに応じた空状態
@Component({
selector: "app-empty-state",
template: `
<div class="empty-state">
<span class="icon" [class]="icon()"></span>
<h3>{{ title() }}</h3>
<p>{{ description() }}</p>
@if (actionLabel()) {
<button (click)="action.emit()" class="btn-primary">
{{ actionLabel() }}
</button>
}
</div>
`,
})
export class EmptyStateComponent {
icon = input("inbox");
title = input.required<string>();
description = input("");
actionLabel = input<string | null>(null);
action = output<void>();
}
フォームパターン
ローディングとバリデーションを備えたフォーム
@Component({
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-field">
<label for="name">名前</label>
<input
id="name"
formControlName="name"
[class.error]="isFieldInvalid('name')"
/>
@if (isFieldInvalid("name")) {
<span class="error-text">
{{ getFieldError("name") }}
</span>
}
</div>
<div class="form-field">
<label for="email">メールアドレス</label>
<input id="email" type="email" formControlName="email" />
@if (isFieldInvalid("email")) {
<span class="error-text">
{{ getFieldError("email") }}
</span>
}
</div>
<button type="submit" [disabled]="form.invalid || submitting()">
@if (submitting()) {
<app-spinner size="sm" /> 送信中...
} @else {
送信
}
</button>
</form>
`,
})
export class UserFormComponent {
private fb = inject(FormBuilder);
submitting = signal(false);
form = this.fb.group({
name: ["", [Validators.required, Validators.minLength(2)]],
email: ["", [Validators.required, Validators.email]],
});
isFieldInvalid(field: string): boolean {
const control = this.form.get(field);
return control ? control.invalid && control.touched : false;
}
getFieldError(field: string): string {
const control = this.form.get(field);
if (control?.hasError("required")) return "このフィールドは必須です";
if (control?.hasError("email")) return "メールアドレスの形式が無効です";
if (control?.hasError("minlength")) return "短すぎます";
return "";
}
async onSubmit() {
if (this.form.invalid) return;
this.submitting.set(true);
try {
await this.service.submit(this.form.value);
this.toast.success("送信に成功しました");
} catch {
this.toast.error("送信に失敗しました");
} finally {
this.submitting.set(false);
}
}
}
ダイアログ/モーダルパターン
確認ダイアログ
// dialog.service.ts
@Injectable({ providedIn: 'root' })
export class DialogService {
private dialog = inject(Dialog); // CDK Dialog またはカスタム
async confirm(options: {
title: string;
message: string;
confirmText?: string;
cancelText?: string;
}): Promise<boolean> {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
data: options,
});
return await firstValueFrom(dialogRef.closed) ?? false;
}
}
// 使用例
async deleteItem(item: Item) {
const confirmed = await this.dialog.confirm({
title: 'アイテムを削除',
message: `"${item.name}" を削除してもよろしいですか?`,
confirmText: '削除',
});
if (confirmed) {
await this.store.delete(item.id);
}
}
アンチパターン
ローディング状態
// 間違い - データが存在する場合にスピナーを表示(再取得時にフラッシュが発生)
@if (loading()) {
<app-spinner />
}
// 正しい - データがない場合のみローディングを表示
@if (loading() && !items().length) {
<app-spinner />
}
エラーハンドリング
// 間違い - エラーが飲み込まれている
try {
await this.service.save();
} catch (e) {
console.log(e); // ユーザーは何も知らない!
}
// 正しい - エラーが表示される
try {
await this.service.save();
} catch (e) {
console.error("保存失敗:", e);
this.toast.error("保存に失敗しました。もう一度お試しください。");
}
ボタン状態
<!-- 間違い - 送信中にボタンが無効化されていない -->
<button (click)="submit()">送信</button>
<!-- 正しい - 無効化され、ローディングが表示される -->
<button (click)="submit()" [disabled]="loading()">
@if (loading()) {
<app-spinner size="sm" />
} 送信
</button>
UI 状態チェックリスト
UIコンポーネントを完了する前に:
UI 状態
- エラー状態が処理され、ユーザーに表示されている
- ローディング状態はデータが存在しない場合のみ表示される
- コレクションに空状態が提供されている(
@emptyブロック) - 非同期操作中はボタンが無効化されている
- 適切な場合にボタンにローディングインジケーターが表示されている
データと変更
- すべての非同期操作にエラーハンドリングがある
- すべてのユーザーアクションにフィードバックがある(トースト/視覚的)
- 楽観的更新は失敗時にロールバックする
アクセシビリティ
- ローディング状態がスクリーンリーダーに通知される
- エラーメッセージがフォームフィールドにリンクされている
- 状態変更後のフォーカス管理
他のスキルとの連携
- angular-state-management: 状態管理にSignalストアを使用
- angular: モダンパターン(Signals、@defer)を適用
- testing-patterns: すべてのUI状態をテスト