Communitygithub.com

ComeOnOliver/skillshub

现代 Angular UI 模式,涵盖加载状态、错误处理和数据展示。适用于构建 UI 组件、处理异步数据或管理组件状态。

skillshub 是什么?

该技能提供了一套全面的 Angular UI 模式,专注于处理异步操作和组件状态。它涵盖了五个核心原则:永不展示陈旧 UI、始终显示错误、乐观更新、渐进式展示和优雅降级。技能文档详细描述了加载状态模式(包括骨架屏和旋转指示器的使用场景)、基于 @if/@else/@for/@defer 的控制流模式、错误处理层次结构以及按钮状态模式。关键要点包括:仅在无数据显示时显示加载指示器、绝不容忍静默错误、在异步操作期间禁用触发器,以及为每个列表/集合提供空状态。该技能还包含了反模式示例和 UI 状态清单,以确保组件在所有状态下都能正常运作。支持所有 Angular 平台,并与 angular-state-management 和 testing-patterns 等其他技能集成。

兼容平台~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="No items found" />
    } @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. 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 存储来管理状态
  • 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

相关技能