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>
}
使用帶 Track 的 @for
@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. Toast 通知 → 可恢復的錯誤,使用者可以重試
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區塊) - 按鈕在非同步操作期間已停用
- 按鈕在適當時機顯示載入指示器
資料與變更
- 所有非同步操作都有錯誤處理
- 所有使用者操作都有回饋(Toast / 視覺)
- 樂觀更新在失敗時會復原
無障礙性
- 載入狀態會向螢幕閱讀器宣告
- 錯誤訊息已連結到表單欄位
- 狀態變更後有焦點管理
與其他技能的整合
- angular-state-management:使用 Signal store 管理狀態
- angular:套用現代模式(Signals、@defer)
- testing-patterns:測試所有 UI 狀態