angular-best-practices

$npx mdskill add tranhieutt/software_development_department/angular-best-practices

Provides Angular best practices for components, modules, services, and reactive patterns.

  • Ensures proper observable lifecycle management and change detection strategies.
  • Depends on Angular CLI, TypeScript, RxJS, and Angular core libraries.
  • Analyzes Angular project files and user queries to recommend relevant practices.
  • Delivers code examples and rules via SKILL.md and direct agent responses.

SKILL.md

.github/skills/angular-best-practicesView on GitHub ↗
---
name: angular-best-practices
type: reference
description: "Provides Angular best practices for components, modules, services, and reactive patterns. Use when working with Angular TypeScript files, component templates, NgModules, RxJS observables, or when the user mentions Angular, ng, or Angular CLI."
paths: ["**/*.component.ts", "**/*.service.ts", "**/*.module.ts", "**/angular.json"]
effort: 3
allowed-tools: Read, Glob, Grep, Write, Edit, Bash
user-invocable: true
when_to_use: "When building Angular applications or working with RxJS streams"
---

# Angular Best Practices

## Critical rules (non-obvious)

- **Always unsubscribe** from Observables in `ngOnDestroy` — use `takeUntilDestroyed()` (Angular 16+) or `Subject` + `takeUntil`
- **`ChangeDetectionStrategy.OnPush`**: component only updates when input reference changes or async pipe emits — use for all leaf components
- **Never mutate input objects/arrays**: OnPush won't detect mutation; create new reference instead
- **`trackBy` is mandatory on `*ngFor`** with dynamic lists — without it, every change re-renders all DOM nodes
- **`async` pipe auto-unsubscribes** — prefer it over manual subscription in templates

## Component with OnPush + signals (Angular 17+)

```typescript
@Component({
  selector: "app-product-list",
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    @for (product of products(); track product.id) {
      <app-product-card [product]="product" />
    }
    @if (loading()) { <app-spinner /> }
  `,
})
export class ProductListComponent {
  products = input.required<Product[]>();
  loading = input(false);

  // Computed signal
  total = computed(() => this.products().length);
}
```

## Service with signals store pattern

```typescript
@Injectable({ providedIn: "root" })
export class CartService {
  private _items = signal<CartItem[]>([]);

  items = this._items.asReadonly();
  total = computed(() => this._items().reduce((sum, i) => sum + i.price * i.qty, 0));

  addItem(item: CartItem) {
    this._items.update(items =>
      items.some(i => i.id === item.id)
        ? items.map(i => i.id === item.id ? { ...i, qty: i.qty + 1 } : i)
        : [...items, { ...item, qty: 1 }]
    );
  }
}
```

## HTTP with interceptors

```typescript
// auth interceptor
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  if (!token) return next(req);
  return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })).pipe(
    catchError(err => {
      if (err.status === 401) inject(Router).navigate(["/login"]);
      return throwError(() => err);
    })
  );
};

// Register in app.config.ts
provideHttpClient(withInterceptors([authInterceptor]))
```

## RxJS: key operators (non-obvious behavior)

```typescript
// switchMap: cancels previous — good for search, bad for saves
search$.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap(term => this.api.search(term))  // cancels in-flight request on new input
)

// exhaustMap: ignores new while processing — good for login button
loginClick$.pipe(
  exhaustMap(() => this.auth.login(credentials))  // prevents double-submit
)

// mergeMap: parallel — good for independent operations
ids$.pipe(mergeMap(id => this.api.fetch(id), 3))  // 3 concurrent max

// combineLatest vs withLatestFrom:
// combineLatest: emits when ANY source emits
// withLatestFrom: emits only when primary source emits, takes latest from secondary
primary$.pipe(withLatestFrom(secondary$))  // common for "take latest filter value on button click"
```

## Auto-unsubscribe pattern

```typescript
// Angular 16+ (preferred)
@Component({...})
export class MyComponent {
  private destroyRef = inject(DestroyRef);

  ngOnInit() {
    this.data$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(...);
  }
}

// Before Angular 16
export class MyComponent implements OnDestroy {
  private destroy$ = new Subject<void>();
  ngOnInit() { this.data$.pipe(takeUntil(this.destroy$)).subscribe(...); }
  ngOnDestroy() { this.destroy$.next(); this.destroy$.complete(); }
}
```

## Lazy loading + standalone components

```typescript
// app.routes.ts
export const routes: Routes = [
  {
    path: "admin",
    loadChildren: () => import("./admin/admin.routes").then(m => m.ADMIN_ROUTES),
    canMatch: [adminGuard],
  },
];

// Standalone component (Angular 15+)
@Component({
  standalone: true,
  imports: [CommonModule, RouterModule, ReactiveFormsModule],
  template: `...`,
})
export class ProfileComponent {}
```

## Common pitfalls

| Pitfall | Fix |
|---|---|
| Memory leak from unsubscribed Observable | Use `takeUntilDestroyed()` or `async` pipe |
| `ExpressionChangedAfterChecked` error | Defer with `afterNextRender()` or move to signals |
| Heavy computation in template | Move to `computed()` signal or `pipe(map(...))` |
| `*ngIf` with `async` pipe fetches twice | Use `as` syntax: `*ngIf="data$ \| async as data"` |
| Zone.js performance in loops | Use `ChangeDetectionStrategy.OnPush` + signals |

More from tranhieutt/software_development_department

SkillDescription
agent-healthReads production/traces/agent-metrics.jsonl and displays a per-agent performance summary table for the current or a specified session. Highlights agents with high error rates or OPEN circuit breaker state.
agent-styleProvides the vendored agent-style v0.3.5 prose rule pack as a portable Claude skill. Use when installing, syncing, applying, or auditing SDD Agent-Style support in another project, or when a style-review workflow needs the bundled rules.
annotateRecords unexpected API behaviors, undocumented caveats, version bugs, or non-obvious workarounds into .claude/memory/annotations.md. Use immediately when an undocumented behavior or surprising caveat is discovered during development.
aws-serverlessProvides AWS serverless architecture patterns for Lambda, API Gateway, DynamoDB, SQS, and SAM/CDK. Use when working with AWS serverless files (serverless.yml, CDK stacks) or when the user mentions Lambda, API Gateway, serverless, or AWS SAM.
backend-architectDesigns scalable backend architectures covering microservices, event-driven systems, API gateways, and data stores. Use when designing a backend system or when the user mentions backend architecture, scalability, or distributed systems.
cloud-run-puppeteerDeploys Puppeteer browser automation on Google Cloud Run with Docker. Use when running headless browser tasks on Cloud Run, or when the user mentions Cloud Run, Puppeteer, headless Chrome, or serverless browser automation.
codex-sddAdapts SDD for Codex while preserving Claude Code behavior. Use when working in Codex, setting up Codex compatibility, mapping Claude tools to Codex tools, or explaining how SDD should run outside Claude Code.
database-architectDesigns relational and NoSQL database schemas, indexing strategies, migration plans, and data modeling patterns. Use when designing a database or when the user mentions database architecture, schema design, or data modeling.
db-reviewReviews database schemas, queries, and migrations for correctness, performance, security, and best practices. Use when reviewing SQL migration files or when the user mentions database review, schema review, or query audit.
deep-interviewConducts a structured technical deep-dive to gather detailed requirements, constraints, and decisions from the user. Use when starting a complex feature or when the user wants to be asked structured clarifying questions before implementation.