Skip to content
Skills Library
Programming · Review & audit

angular-best-practices

/angular-best-practices

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.

Licence
MIT
Last repository change
15.05.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
3
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 15.05.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

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.

Original author 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.

How it works

  1. Critical rules (non-obvious)
  2. Component with OnPush + signals (Angular 17+)
  3. Service with signals store pattern
  4. HTTP with interceptors
  5. RxJS: key operators (non-obvious behavior)
  6. Auto-unsubscribe pattern
  7. Lazy loading + standalone components
  8. Common pitfalls
Original SKILL.md headings · 148 lines, 541 words
SKILL.md preview
---
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 |
Files in this package (3)
  • README.md 2 KB
  • SKILL.md 5 KB
  • metadata.json 1 KB

Versions

RepositoryScoreLicence
This page · tranhieutt/software_development_department100MIT
rootcastleco/rei-skills95MIT
LiHongwei-cn/lihongwei-cn95MIT
agent-skills-hub/agent-skills-hub95MIT
pinkpixel-dev/skills-collection-195Apache-2.0
FrancoStino/opencode-skills-collection90MIT

Database snapshot: 13.11.2026 · package version cf58f6653624 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 95angular-rxjs-patterns
    Use when handling async operations in Angular applications with observables, operators, and subjects.
  • 100angular
    Angular 17+ with standalone components and signals. Covers components, services, dependency injection, and reactive patterns. USE WHEN: user mentions "Angular", "standalone components", "signals", "dependency injection", "RxJS", "NgModules", asks about "Angular 17 patterns",…
  • 96angular
    Angular开发专家助手。当用户需要进行Angular前端开发、TypeScript企业级应用、RxJS响应式编程或SPA开发时调用。
  • 100angular
    Angular-specific coding standards and best practices Triggers on: **/*.ts, **/*.html, **/*.scss, **/*.css
  • 100angular-expert
    Expert knowledge in Angular framework, RxJS reactive programming, TypeScript, dependency injection, and enterprise application development. Use when the user mentions RxJS, TypeScript, dependency injection, reactive, frontend, or enterprise, or when the task involves Angular…
  • 100angular-rxjs-interop
    Bridge Observables and Signals using toSignal and toObservable in Angular. Use when converting between RxJS Observables and Angular Signals.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.