angular-best-practices

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Angular Best Practices

Angular 最佳实践

Comprehensive performance optimization guide for Angular applications, containing 45+ rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
这是一份针对Angular应用的全面性能优化指南,包含8个分类下的45+条规则,按影响优先级排序,可指导自动化重构与代码生成。

When to Apply

适用场景

Reference these guidelines when:
  • Writing new Angular components or services
  • Implementing change detection strategies
  • Reviewing code for performance issues
  • Refactoring existing Angular code
  • Optimizing bundle size or load times
  • Working with RxJS observables and state management
  • Implementing forms and validation
  • Writing unit and integration tests
在以下场景中可参考本指南:
  • 编写新的Angular组件或服务
  • 实现变更检测策略
  • 评审代码以排查性能问题
  • 重构现有Angular代码
  • 优化包体积或加载时间
  • 处理RxJS可观察对象与状态管理
  • 实现表单与验证
  • 编写单元测试与集成测试

Rule Categories by Priority

按优先级划分的规则分类

PriorityCategoryImpactPrefix
1Change DetectionCRITICAL
cd-
2Bundle Size OptimizationCRITICAL
bundle-
3Template PerformanceHIGH
template-
4RxJS & Async OperationsHIGH
rxjs-
5Component ArchitectureMEDIUM-HIGH
component-
6HTTP & Data FetchingMEDIUM
http-
7Forms & ValidationMEDIUM
forms-
8Testing & DebuggingLOW-MEDIUM
testing-
优先级分类影响程度前缀
1变更检测关键
cd-
2包体积优化关键
bundle-
3模板性能
template-
4RxJS 与异步操作
rxjs-
5组件架构中高
component-
6HTTP 与数据获取
http-
7表单与验证
forms-
8测试与调试中低
testing-

Quick Reference

快速参考

1. Change Detection (CRITICAL)

1. 变更检测(关键)

  • cd-onpush
    - Use OnPush change detection strategy
  • cd-trackby
    - Always use trackBy in *ngFor
  • cd-pure-pipes
    - Prefer pure pipes over methods in templates
  • cd-immutable-data
    - Use immutable data patterns
  • cd-detach-reattach
    - Detach change detection for heavy computations
  • cd-run-outside-angular
    - Run non-UI code outside NgZone
  • cd-onpush
    - 使用OnPush变更检测策略
  • cd-trackby
    - 在*ngFor中始终使用trackBy
  • cd-pure-pipes
    - 优先在模板中使用纯管道而非方法
  • cd-immutable-data
    - 使用不可变数据模式
  • cd-detach-reattach
    - 针对繁重计算,分离并重新附加变更检测
  • cd-run-outside-angular
    - 在NgZone之外运行非UI代码

2. Bundle Size Optimization (CRITICAL)

2. 包体积优化(关键)

  • bundle-lazy-loading
    - Lazy load feature modules
  • bundle-tree-shaking
    - Ensure tree-shakeable providers
  • bundle-standalone-components
    - Use standalone components
  • bundle-defer-views
    - Use @defer for heavy components
  • bundle-preload-strategies
    - Implement smart preloading
  • bundle-avoid-barrel-exports
    - Import directly, avoid barrel files
  • bundle-lazy-loading
    - 懒加载功能模块
  • bundle-tree-shaking
    - 确保提供者支持摇树优化
  • bundle-standalone-components
    - 使用独立组件
  • bundle-defer-views
    - 为重型组件使用@defer
  • bundle-preload-strategies
    - 实现智能预加载策略
  • bundle-avoid-barrel-exports
    - 直接导入,避免使用桶文件

3. Template Performance (HIGH)

3. 模板性能(高)

  • template-avoid-function-calls
    - Avoid function calls in templates
  • template-async-pipe
    - Use async pipe instead of manual subscriptions
  • template-ng-container
    - Use ng-container for structural directives
  • template-control-flow
    - Use new control flow syntax (@if, @for)
  • template-optimize-ngif-ngfor
    - Never use *ngIf and *ngFor on same element
  • template-image-optimization
    - Use NgOptimizedImage directive
  • template-avoid-function-calls
    - 避免在模板中调用函数
  • template-async-pipe
    - 使用async管道而非手动订阅
  • template-ng-container
    - 为结构型指令使用ng-container
  • template-control-flow
    - 使用新的控制流语法(@if、@for)
  • template-optimize-ngif-ngfor
    - 切勿在同一元素上同时使用ngIf和ngFor
  • template-image-optimization
    - 使用NgOptimizedImage指令

4. RxJS & Async Operations (HIGH)

4. RxJS 与异步操作(高)

  • rxjs-avoid-nested-subscriptions
    - Never nest subscriptions
  • rxjs-unsubscribe
    - Always unsubscribe (takeUntilDestroyed, DestroyRef)
  • rxjs-share-replay
    - Use shareReplay for HTTP caching
  • rxjs-switchmap-vs-mergemap
    - Choose correct flattening operator
  • rxjs-signals-vs-observables
    - Prefer signals for synchronous state
  • rxjs-debounce-throttle
    - Debounce user input events
  • rxjs-avoid-nested-subscriptions
    - 切勿嵌套订阅
  • rxjs-unsubscribe
    - 始终取消订阅(使用takeUntilDestroyed、DestroyRef)
  • rxjs-share-replay
    - 使用shareReplay实现HTTP缓存
  • rxjs-switchmap-vs-mergemap
    - 选择正确的展平操作符
  • rxjs-signals-vs-observables
    - 针对同步状态优先使用Signals
  • rxjs-debounce-throttle
    - 对用户输入事件进行防抖处理

5. Component Architecture (MEDIUM-HIGH)

5. 组件架构(中高)

  • component-smart-presentational
    - Separate smart and presentational components
  • component-input-transforms
    - Use input transforms for data conversion
  • component-output-naming
    - Follow output naming conventions
  • component-content-projection
    - Use content projection effectively
  • component-dynamic-components
    - Load components dynamically when needed
  • component-host-directives
    - Compose behavior with host directives
  • component-smart-presentational
    - 分离智能组件与展示组件
  • component-input-transforms
    - 使用输入转换进行数据转换
  • component-output-naming
    - 遵循输出命名规范
  • component-content-projection
    - 有效使用内容投影
  • component-dynamic-components
    - 在需要时动态加载组件
  • component-host-directives
    - 使用宿主指令组合行为

6. HTTP & Data Fetching (MEDIUM)

6. HTTP 与数据获取(中)

  • http-interceptors
    - Use interceptors for cross-cutting concerns
  • http-caching
    - Implement HTTP caching strategies
  • http-retry-logic
    - Add retry logic for resilience
  • http-cancel-requests
    - Cancel pending requests on navigation
  • http-typed-responses
    - Always type HTTP responses
  • http-error-handling
    - Implement centralized error handling
  • http-interceptors
    - 使用拦截器处理横切关注点
  • http-caching
    - 实现HTTP缓存策略
  • http-retry-logic
    - 添加重试逻辑以提升韧性
  • http-cancel-requests
    - 在导航时取消待处理请求
  • http-typed-responses
    - 始终为HTTP响应添加类型
  • http-error-handling
    - 实现集中式错误处理

7. Forms & Validation (MEDIUM)

7. 表单与验证(中)

  • forms-reactive-over-template
    - Prefer reactive forms for complex forms
  • forms-typed-forms
    - Use strictly typed reactive forms
  • forms-custom-validators
    - Create reusable custom validators
  • forms-async-validation
    - Debounce async validators
  • forms-control-value-accessor
    - Implement ControlValueAccessor correctly
  • forms-form-arrays
    - Handle dynamic form arrays efficiently
  • forms-reactive-over-template
    - 复杂表单优先使用响应式表单
  • forms-typed-forms
    - 使用严格类型的响应式表单
  • forms-custom-validators
    - 创建可复用的自定义验证器
  • forms-async-validation
    - 对异步验证器进行防抖处理
  • forms-control-value-accessor
    - 正确实现ControlValueAccessor
  • forms-form-arrays
    - 高效处理动态表单数组

8. Testing & Debugging (LOW-MEDIUM)

8. 测试与调试(中低)

  • testing-component-harness
    - Use component harnesses
  • testing-mock-services
    - Mock services properly
  • testing-async-testing
    - Use fakeAsync/tick for async tests
  • testing-change-detection
    - Trigger change detection in tests
  • testing-marble-testing
    - Use marble testing for RxJS
  • testing-performance-profiling
    - Profile with Angular DevTools
  • testing-component-harness
    - 使用组件测试工具(Component Harnesses)
  • testing-mock-services
    - 正确模拟服务
  • testing-async-testing
    - 使用fakeAsync/tick处理异步测试
  • testing-change-detection
    - 在测试中触发变更检测
  • testing-marble-testing
    - 为RxJS使用大理石测试
  • testing-performance-profiling
    - 使用Angular DevTools进行性能分析

How to Use

使用方法

Read individual rule files for detailed explanations and code examples:
rules/cd-onpush.md
rules/bundle-lazy-loading.md
rules/_sections.md
Each rule file contains:
  • Brief explanation of why it matters
  • Incorrect code example with explanation
  • Correct code example with explanation
  • Additional context and references
阅读单个规则文件以获取详细说明和代码示例:
rules/cd-onpush.md
rules/bundle-lazy-loading.md
rules/_sections.md
每个规则文件包含:
  • 简要说明该规则的重要性
  • 错误代码示例及解释
  • 正确代码示例及解释
  • 额外背景信息与参考资料

Full Compiled Document

完整编译文档

For the complete guide with all rules expanded:
AGENTS.md
如需查看包含所有扩展规则的完整指南,请参阅:
AGENTS.md