Communitygithub.com

ComeOnOliver/skillshub

現代 Angular UI 模式,適用於載入狀態、錯誤處理和資料顯示。在建立 UI 元件、處理非同步資料或管理元件狀態時使用。

skillshub 是什麼?

此技能提供了一套完整、現代化的 Angular UI 模式指南,專注於解決載入狀態、錯誤處理、按鈕狀態、空狀態及表單等常見場景。它強調以使用者體驗為核心,遵循「永不顯示過時 UI」、「始終呈現錯誤」、「樂觀更新」、「漸進式揭露」和「優雅降級」等核心原則。此技能支援所有現代 Angular 專案,特別是使用 Signals、`@defer`、`@if/@else` 和 `@for` 等新控制流的專案。文件中包含大量可複製的 TypeScript 範例程式碼、決策流程圖和反模式對比,幫助開發者避免常見陷阱,建立既健壯又反應迅速的應用程式。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/sickn33/angular-ui-patterns

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Angular UI 模式

核心原則

  1. 永不顯示過時 UI - 僅在實際載入時顯示載入狀態
  2. 始終呈現錯誤 - 使用者必須知道何時發生錯誤
  3. 樂觀更新 - 讓 UI 感覺即時響應
  4. 漸進式揭露 - 使用 @defer 在可用時顯示內容
  5. 優雅降級 - 部分資料總比沒有資料好

載入狀態模式

黃金法則

只有在沒有資料可顯示時,才顯示載入指示器。

@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 狀態

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

相關技能