--- name: angular-standards description: "Use when writing, editing, or reviewing Angular code (components, templates, services, routing, forms, HTTP, SSR, tests): which Angular rules win when sources disagree, the andes non-negotiables — standalone, signals-first and zoneless, native control flow, inject(), Signal Store for state — and the angular-cli MCP grounding workflow." --- # Angular standards Andes follows Angular's own rules. When sources disagree, the higher one wins: 1. **angular.dev** — the style guide, the version's best practices (`get_best_practices`), and the guides. 2. **The CLI's default output** — what `ng generate` produces with no naming overrides. 3. **The `angular-developer` skill** — read the `references/` file matching the work. 4. **Andes add-ons**, only where the sources above are silent: this file, `ngrx-signal-store` for state, and `angular-ui-architecture` for folders, names, path aliases, and layer lint. An add-on that contradicts a higher source is a bug — follow Angular and say so. ## Workflow 1. Ground in the workspace's pinned version with the `angular-cli` MCP server: `list_projects` (workspace path, Angular version, test framework, style language) → `get_best_practices` with that `workspacePath` (without it when there is no `angular.json`) → `search_documentation` whenever an API or version behavior is uncertain. Don't assert version-specific behavior from memory. 2. Follow the project's own conventions first (the style guide's "prefer consistency"; naming per `angular-ui-architecture`); reuse existing code; keep changes small. 3. After changing code, run `ng build`, then `ng test --watch=false` when specs exist or were added. Never run `ng update` unless asked. ## Non-negotiables - **Components** — standalone only, never `standalone: true` (the default since v19); on v22+ OnPush is the default, so a new component sets no `changeDetection`, and one `ng update` marked `ChangeDetectionStrategy.Eager` keeps it until it is moved to OnPush deliberately; below v22 set `ChangeDetectionStrategy.OnPush` on every component; `input()` / `output()` / `model()` and signal queries (`viewChild()`, `contentChildren()`, …), never their decorators; `readonly` on those properties and `protected` on members only the template reads; the `host` object, not `@HostBinding` / `@HostListener`; self-closing tags for elements without content. - **Templates** — native `@if` / `@for` / `@switch`, never `*ngIf` / `*ngFor` / `*ngSwitch`; every `@for` tracked on stable identity (not `$index` for mutable collections), `@empty` where the list can be empty; avoid complex logic — derive with `computed()`, and bind events to a method named for what it does (`(click)="save()"`); `class` / `style` bindings, never `ngClass` / `ngStyle`; import only the directives and pipes the template uses, never `CommonModule`; never `` inside `@if` / `@for` / `@switch`; `@defer` never on above-the-fold or LCP content. - **Signals** — derive with `computed()` / `linkedSignal()`; `effect()` only to sync signals to non-signal APIs, never to propagate state; never write signals inside `computed()`; always call signals (`sig()`) and read them before any `await` in a reactive context; prefer `toSignal()` / `resource()` / `httpResource()` over manual `subscribe()`, and guard a resource's `value()` with `hasValue()`; unavoidable subscriptions get `takeUntilDestroyed()`. - **DI** — `inject()`, not constructor parameters, and only in a valid injection context; new singletons use `@Service()` on v22+ (`@Service({ autoProvided: false })` plus a `providers:` entry for a scoped lifetime) and `@Injectable({ providedIn: 'root' })` below v22; a custom creation factory is `@Service({ factory: () => … })` (root-provided only; it cannot combine with `autoProvided: false`); keep `@Injectable` only for what `@Service` cannot do (`useClass` / `useValue` / `useExisting`, non-root scopes); component and route `providers` only for deliberately scoped lifetimes. - **State** — non-trivial state in a `signalStore`, never a hand-rolled `BehaviorSubject` service; no classic NgRx actions/reducers/effects unless the Events plugin is a deliberate choice. Everything else (protected state, updaters, `httpResource` vs `rxMethod` vs `signalMethod`, entities, store scope) follows `ngrx-signal-store`'s production defaults and decision rules. - **Routing** — `loadComponent` / `loadChildren` for every route except the primary landing page, which loads eagerly; functional guards and resolvers, and no guard relying on work an earlier guard in the same array does (they run concurrently); `withComponentInputBinding()` over `ActivatedRoute` plumbing; a `title` on every route; route-level `providers` for route-scoped stores. - **Forms** — Signal Forms for new forms on v22+; otherwise the app's existing strategy, and Reactive over template-driven for a new form; on zoneless apps Reactive form updates (`setValue`, `patchValue`, `FormArray.push`) schedule no change detection, so feed the template through signals (`toSignal(form.valueChanges)`) or `markForCheck()`; no `any`-typed form values; validation errors surfaced accessibly. - **HTTP** — `httpResource` for reads on v22+ (experimental before; there, `HttpClient` through `rxMethod` or `toSignal()`), `HttpClient` for mutations; `provideHttpClient(...)` only to configure features (interceptors, XSRF, `withXhr()` for upload progress) — v21+ injects `HttpClient` without it, but a cookie-authenticated app calls `provideHttpClient()` for Angular's XSRF interceptor; functional interceptors; a response's generic type is an assertion, so validate untrusted data at runtime; no nested `subscribe()` chains; errors surfaced — `httpResource` exposes `status()` and `error()`, and `rxMethod` loads store them per the skill's request-status pattern — never swallowed or console-only. - **SSR / hydration** — inject `DOCUMENT` instead of the global `document`; no `window` / `localStorage` during construction or in `computed()`; DOM work in `afterNextRender` / `afterRenderEffect`; async work that must finish before serialization runs through `PendingTasks` (zoneless apps get no zone.js stability); valid HTML structure; on v22+ `provideClientHydration()` already enables incremental hydration and event replay — never the deprecated `withIncrementalHydration()`; `ngSkipHydration` only as a documented temporary workaround. - **Security** — interpolation over `[innerHTML]` with untrusted data; never `bypassSecurityTrust*` without documented justification; no direct DOM APIs without sanitization; no URLs built from raw user input; no secrets in client code or `environment.*` files. - **Accessibility** — passes AXE checks and WCAG AA; semantic elements over clickable `div`s; keyboard operability and visible focus; labeled controls; Angular Aria's `ng*` directives for accordion, listbox, combobox, menu, tabs, toolbar, tree, and grid patterns when the design system does not ship them; focus management for dialogs and route changes. - **Styling & animations** — no `::ng-deep`; native `animate.enter` / `animate.leave` (v20.2+), not the deprecated `@angular/animations`; `NgOptimizedImage` for static images. - **Zoneless & performance** — zoneless is the default on v21+ (v20: `provideZonelessChangeDetection()`), so never add `provideZoneChangeDetection()` or rely on zone.js patching (`NgZone.onStable` / `onUnstable` / `isStable` / `onMicrotaskEmpty`) — `NgZone.run` / `runOutsideAngular` stay, removing them can regress zone-based hosts; no impure pipes, and never inject a pipe class to call `transform()`; strict TypeScript — no `any`, use `unknown` and narrow. - **Tooling** — `ng add` for Angular libraries, never a bare `npm install`; `ng generate` with the CLI's default naming; the `ng generate @angular/core:` schematics over hand edits when modernizing (`@angular/core:service` needs v22.1 and skips constructor-injected classes, so run the `inject` migration first). - **Tests** — the framework `list_projects` reports (Vitest on current versions); on v21+ `TestBed` is zoneless by default, so add no change-detection provider (v20: `provideZonelessChangeDetection()`); new or rewritten specs `await fixture.whenStable()`, not `fixture.detectChanges()`, `fakeAsync`, or `fixture.changeDetectorRef.markForCheck()` (existing `detectChanges()` suites stay, per angular.dev); component harnesses; `RouterTestingHarness` for routing, never a mocked `Router`; store specs per `ngrx-signal-store` `references/testing.md`. Cover the critical paths of what changed.