Angular Idioms and Patterns
Core Philosophy
Angular (19+) rewards signals, standalone components, and reactive patterns. Idiomatic Angular = typed, modular, RxJS-aware, OnPush by default.
Scope: This file covers Angular-specific coding idioms for components, services, and patterns. For TypeScript type system patterns, see @.agents/skills/typescript-idioms/SKILL.md. For file and folder layout, see references/project-structure.md.
Loading guard: Do NOT load this skill for non-Angular projects. Vue → vue-idioms; React → react-idioms; Next.js → nextjs-idioms. Angular file suffixes (.component.ts, .service.ts, etc.) and angular.json are the reliable triggers — tsconfig*.json alone is NOT an Angular signal (every TS project has one).
When to Load References
Load these before writing code in the matching context — not after.
| Situation |
Reference to Load |
| Starting an Angular project or reviewing file layout |
references/project-structure.md |
| TypeScript type system, async, Zod, error types |
@.agents/skills/typescript-idioms/SKILL.md (always co-load) |
| Zod schemas / boundary validation |
@.agents/skills/typescript-idioms/references/zod-patterns.md |
| Async / I/O / coercion / RxJS pitfalls |
@.agents/skills/typescript-idioms/references/ts-patterns-and-anti-patterns.md |
Standalone Components (Default)
Standalone components — no NgModules for new components (standalone is the default since Angular 19):
@Component({
selector: 'app-task-list',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [TaskCardComponent],
template: `
@for (task of filteredTasks(); track task.id) {
<app-task-card [task]="task" />
}
`
})
export class TaskListComponent {
tasks = signal<Task[]>([]);
}
Lazy-load routes with loadComponent:
{ path: 'tasks', loadComponent: () => import('./features/task/task-list.component')
.then(m => m.TaskListComponent) }
Signals (17+)
- Signals for synchronous state — prefer over BehaviorSubject for component state.
computed for derived state. effect for side effects.
- RxJS for async streams — HTTP, WebSocket, complex event handling.
// ✅ Signal-based component state
export class TaskListComponent {
private readonly taskService = inject(TaskService);
tasks = signal<Task[]>([]);
filter = signal<string>('');
filteredTasks = computed(() => // ✅ Derived state
this.tasks().filter(t => t.title.includes(this.filter()))
);
constructor() {
effect(() => console.debug('Tasks updated:', this.tasks().length)); // ✅ Side effect
}
}
Change Detection
OnPush is the default strategy — set it on every component:
// ✅ Always OnPush
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
// ...
})
OnPush works naturally with signals — signal reads in templates automatically trigger change detection when the signal value changes.
Use Default only when wrapping third-party components that mutate state imperatively and cannot be refactored.
Never call ChangeDetectorRef.detectChanges() manually — if you need it, your data flow is wrong. Convert to signals or use async pipe.
Component Design
Signal-based inputs and outputs (Angular 17.1+) — prefer over decorators:
// ✅ Signal input — reactive, no OnChanges needed
task = input.required<Task>();
variant = input<'compact' | 'full'>('full');
// ✅ Signal output
taskCompleted = output<string>();
// ❌ Decorator style — legacy
@Input() task!: Task;
@Output() taskCompleted = new EventEmitter<string>();
Content projection — use <ng-content> for composable UI, select attribute for named slots:
@Component({
template: `
<header><ng-content select="[card-header]" /></header>
<main><ng-content /></main>
`
})
Signal-based view queries (Angular 17.2+):
canvas = viewChild.required<ElementRef>('canvas'); // ✅ Reactive, no AfterViewInit
items = contentChildren(TabItemComponent); // ✅ Content query
Lifecycle hooks guidance:
OnInit — fetch initial data, set up subscriptions (use inject(DestroyRef) for cleanup)
OnDestroy — manual cleanup only if takeUntilDestroyed or DestroyRef cannot be used
- Avoid
OnChanges — use signal inputs with computed() or effect() instead
Template Patterns
Use new control flow syntax (Angular 17+) — @for, @if, @switch, @defer:
<!-- ✅ New control flow with track expression -->
@for (task of tasks(); track task.id) {
<app-task-card [task]="task" />
} @empty {
<p>No tasks found.</p>
}
@if (isLoading()) {
<app-spinner />
} @else {
<app-task-list [tasks]="tasks()" />
}
@switch (task().priority) {
@case ('high') { <span class="badge-high">High</span> }
@case ('medium') { <span class="badge-med">Medium</span> }
@default { <span class="badge-low">Low</span> }
}
@defer for lazy-loaded template blocks:
<!-- ✅ Lazy-load heavy component -->
@defer (on viewport) {
<app-task-analytics [tasks]="tasks()" />
} @placeholder {
<div class="skeleton" />
}
Use ng-container for grouping without extra DOM nodes — e.g., <ng-container *ngTemplateOutlet="tpl" />.
Avoid complex expressions in templates — extract to computed():
// ❌ template: `{{ tasks().filter(t => t.done).length }} / {{ tasks().length }}`
// ✅ Extract to computed
summary = computed(() => `${this.doneTasks().length} / ${this.tasks().length}`);
Dependency Injection
inject() function over constructor injection in standalone components.
- Provide at appropriate level — component, route, or root.
- Abstract services behind interfaces for testability:
// ✅ Abstract class as interface (TypeScript has no runtime interfaces)
export abstract class TaskStorage {
abstract getById(id: string): Observable<Task>;
abstract save(task: Task): Observable<void>;
}
// ✅ Implementation
@Injectable()
export class HttpTaskStorage extends TaskStorage {
private readonly http = inject(HttpClient);
getById(id: string) { return this.http.get<Task>(`/api/tasks/${id}`); }
save(task: Task) { return this.http.post<void>('/api/tasks', task); }
}
// ✅ Wired at route or root level
providers: [{ provide: TaskStorage, useClass: HttpTaskStorage }]
Reactive Forms
- Reactive forms over template-driven for complex forms.
- Typed forms (
FormControl<string>) — always.
- Custom validators as pure functions:
// ✅ Typed form group with nonNullable controls
export class TaskFormComponent {
form = new FormGroup({
title: new FormControl('', { nonNullable: true,
validators: [Validators.required, Validators.maxLength(200)] }),
priority: new FormControl<'low' | 'medium' | 'high'>('medium', { nonNullable: true }),
});
}
Routing Patterns
Functional guards (Angular 15+) — no class-based guards:
// ✅ Functional guard
export const authGuard: CanActivateFn = (route, state) => {
const auth = inject(AuthService);
return auth.isAuthenticated() || inject(Router).createUrlTree(['/login']);
};
// ❌ Class-based guard — deprecated
@Injectable() export class AuthGuard implements CanActivate { ... }
Functional resolvers — same pattern, use ResolveFn<T>:
export const taskResolver: ResolveFn<Task> = (route) =>
inject(TaskService).getById(route.paramMap.get('id')!);
Lazy loading with loadChildren for feature routes:
{
path: 'tasks',
loadChildren: () => import('./features/task/task.routes')
.then(m => m.TASK_ROUTES),
canActivate: [authGuard],
}
Route parameter binding with input() (Angular 16+):
// In app.config.ts: withComponentInputBinding()
// ✅ Route params bound as signal inputs — no ActivatedRoute needed
taskId = input.required<string>();
// ❌ Manual route param subscription
this.route.paramMap.pipe(...).subscribe(...)
State Management
Component signals first — sufficient for most local UI state.
NgRx Signal Store for shared or complex state beyond a single component:
// ✅ NgRx Signal Store
export const TaskStore = signalStore(
{ providedIn: 'root' },
withState<TaskState>({ tasks: [], isLoading: false, error: null }),
withComputed(({ tasks }) => ({
completedTasks: computed(() => tasks().filter(t => t.done)),
})),
withMethods((store, taskService = inject(TaskService)) => ({
async loadTasks(): Promise<void> {
patchState(store, { isLoading: true });
const tasks = await firstValueFrom(taskService.getAll());
patchState(store, { tasks, isLoading: false });
},
})),
);
When to use what:
signal() — local component state, simple parent-child data flow
- NgRx Signal Store — shared state across components, entity management (
withEntities())
- RxJS + services — real-time streams, WebSocket data, complex async orchestration
Error Handling
For universal error handling principles, see .agents/rules/error-handling-principles.md. Below: Angular-specific patterns only.
Global error handler for uncaught exceptions:
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
handleError(error: unknown): void {
this.logger.error('unhandled_error', { error }); // Log to observability platform
}
}
HTTP interceptor for centralized error handling:
export const errorInterceptor: HttpInterceptorFn = (req, next) =>
next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
// Redirect to login
}
return throwError(() => error);
})
);
RxJS error handling — never leave Observables unhandled. Always use catchError in .pipe() or handle in subscribe() error callback.
Anti-Patterns
- ❌ NgModules for new components — use standalone components (default since v19)
- ❌ BehaviorSubject for simple component state — use signals
- ❌ Constructor injection in standalone components — use
inject()
- ❌ Manual subscriptions without cleanup — use
takeUntilDestroyed() or async pipe
- ❌
any in template bindings — type everything
- ❌ Direct DOM manipulation — use Angular's renderer or signals
- ❌
subscribe() in components without unsubscribe — prefer async pipe or toSignal()
- ❌
ChangeDetectionStrategy.Default without justification — always OnPush
- ❌
*ngFor / *ngIf in new code — use @for / @if control flow
- ❌ Class-based guards and resolvers — use functional equivalents
// ❌ Memory leak — subscription never cleaned up
ngOnInit() {
this.taskService.getTasks().subscribe(tasks => this.tasks = tasks);
}
// ✅ Auto-cleanup with takeUntilDestroyed
private destroyRef = inject(DestroyRef);
ngOnInit() {
this.taskService.getTasks().pipe(
takeUntilDestroyed(this.destroyRef)
).subscribe(tasks => this.tasks.set(tasks));
}
// ✅ Even better — convert to signal
tasks = toSignal(this.taskService.getTasks(), { initialValue: [] });
Naming Conventions
File naming — dot-separated with type suffix:
task-list.component.ts, task.service.ts, task.pipe.ts, task.guard.ts, task.directive.ts
task.routes.ts for feature route definitions
task-list.component.spec.ts for tests (co-located)
Selector prefixes — use app- (or project-specific prefix from angular.json): selector: 'app-task-card'
Class naming — suffix matches file type: TaskListComponent, TaskService, HighlightDirective, DateFormatPipe
Route file exports — UPPER_SNAKE_CASE: export const TASK_ROUTES: Routes = [...]
Testing
For universal testing principles, see .agents/rules/testing-strategy.md. Below: Angular-specific patterns only.
Test-file naming: *.spec.ts co-located (Angular CLI default — .component.spec.ts beside .component.ts). For the cross-framework reconciliation rule, see @.agents/skills/typescript-idioms/references/project-structure.md §Test Organization.
Angular Testing Library for component tests (preferred over TestBed):
import { render, screen } from '@testing-library/angular';
it('should display task title', async () => {
await render(TaskCardComponent, {
componentInputs: { task: mockTask },
});
expect(screen.getByText('Deploy fix')).toBeInTheDocument();
});
Spectator for service tests:
const spectator = createServiceFactory({
service: TaskService,
mocks: [TaskStorage],
});
HttpTestingController for HTTP service tests — no live backend.
Signal Store testing — test store methods directly, assert signal values:
it('should load tasks', async () => {
const store = TestBed.inject(TaskStore);
await store.loadTasks();
expect(store.tasks().length).toBeGreaterThan(0);
});
Formatting and Static Analysis
| Tool |
Purpose |
Command |
| Prettier |
Formatting |
npx prettier --write . |
| ESLint + angular-eslint |
Linting |
npx ng lint |
strict mode |
Type checking |
"strict": true in tsconfig.json |
| Angular compiler |
Template checking |
npx ng build (checks templates) |
Related
- Code Idioms and Conventions @.agents/rules/code-idioms-and-conventions.md
- TypeScript Idioms @.agents/skills/typescript-idioms/SKILL.md
- Angular Project Structure @.agents/skills/angular-idioms/references/project-structure.md
- Frontend Layout (framework-neutral, shared with React/Vue) @.agents/skills/frontend-design/references/frontend-layout.md
- Frontend Design @.agents/skills/frontend-design/SKILL.md
- Security Principles @.agents/rules/security-principles.md
- Accessibility Principles @.agents/rules/accessibility-principles.md
- Testing Strategy @.agents/rules/testing-strategy.md
- Error Handling Principles @.agents/rules/error-handling-principles.md
- Logging and Observability @.agents/rules/logging-and-observability-mandate.md
- Architectural Patterns @.agents/rules/architectural-pattern.md
1---2name: angular-idioms-23description: Angular components, signals, DI, RxJS, standalone architecture. For TypeScript see typescript-idioms.4---56## Angular Idioms and Patterns78### Core Philosophy910Angular (19+) rewards signals, standalone components, and reactive patterns. Idiomatic Angular = typed, modular, RxJS-aware, OnPush by default.1112> **Scope:** This file covers Angular-specific coding idioms for components, services, and patterns. For TypeScript type system patterns, see `@.agents/skills/typescript-idioms/SKILL.md`. For file and folder layout, see `references/project-structure.md`.13>14> **Loading guard:** Do NOT load this skill for non-Angular projects. Vue → `vue-idioms`; React → `react-idioms`; Next.js → `nextjs-idioms`. Angular file suffixes (`.component.ts`, `.service.ts`, etc.) and `angular.json` are the reliable triggers — `tsconfig*.json` alone is NOT an Angular signal (every TS project has one).1516## When to Load References1718> Load these **before** writing code in the matching context — not after.1920| Situation | Reference to Load |21|---|---|22| Starting an Angular project or reviewing file layout | `references/project-structure.md` |23| TypeScript type system, async, Zod, error types | `@.agents/skills/typescript-idioms/SKILL.md` (always co-load) |24| Zod schemas / boundary validation | `@.agents/skills/typescript-idioms/references/zod-patterns.md` |25| Async / I/O / coercion / RxJS pitfalls | `@.agents/skills/typescript-idioms/references/ts-patterns-and-anti-patterns.md` |2627### Standalone Components (Default)28291. **Standalone components** — no NgModules for new components (standalone is the default since Angular 19):30 ```typescript31 @Component({32 selector: 'app-task-list',33 changeDetection: ChangeDetectionStrategy.OnPush,34 imports: [TaskCardComponent],35 template: `36 @for (task of filteredTasks(); track task.id) {37 <app-task-card [task]="task" />38 }39 `40 })41 export class TaskListComponent {42 tasks = signal<Task[]>([]);43 }44 ```45462. **Lazy-load routes** with `loadComponent`:47 ```typescript48 { path: 'tasks', loadComponent: () => import('./features/task/task-list.component')49 .then(m => m.TaskListComponent) }50 ```5152### Signals (17+)53541. **Signals for synchronous state** — prefer over BehaviorSubject for component state.552. **`computed`** for derived state. **`effect`** for side effects.563. **RxJS for async streams** — HTTP, WebSocket, complex event handling.5758```typescript59// ✅ Signal-based component state60export class TaskListComponent {61 private readonly taskService = inject(TaskService);62 tasks = signal<Task[]>([]);63 filter = signal<string>('');64 filteredTasks = computed(() => // ✅ Derived state65 this.tasks().filter(t => t.title.includes(this.filter()))66 );67 constructor() {68 effect(() => console.debug('Tasks updated:', this.tasks().length)); // ✅ Side effect69 }70}71```7273### Change Detection74751. **`OnPush` is the default strategy** — set it on every component:76 ```typescript77 // ✅ Always OnPush78 @Component({79 changeDetection: ChangeDetectionStrategy.OnPush,80 // ...81 })82 ```83842. **OnPush works naturally with signals** — signal reads in templates automatically trigger change detection when the signal value changes.85863. **Use `Default` only when** wrapping third-party components that mutate state imperatively and cannot be refactored.87884. **Never call `ChangeDetectorRef.detectChanges()` manually** — if you need it, your data flow is wrong. Convert to signals or use `async` pipe.8990### Component Design91921. **Signal-based inputs and outputs** (Angular 17.1+) — prefer over decorators:93 ```typescript94 // ✅ Signal input — reactive, no OnChanges needed95 task = input.required<Task>();96 variant = input<'compact' | 'full'>('full');9798 // ✅ Signal output99 taskCompleted = output<string>();100101 // ❌ Decorator style — legacy102 @Input() task!: Task;103 @Output() taskCompleted = new EventEmitter<string>();104 ```1051062. **Content projection** — use `<ng-content>` for composable UI, `select` attribute for named slots:107 ```typescript108 @Component({109 template: `110 <header><ng-content select="[card-header]" /></header>111 <main><ng-content /></main>112 `113 })114 ```1151163. **Signal-based view queries** (Angular 17.2+):117 ```typescript118 canvas = viewChild.required<ElementRef>('canvas'); // ✅ Reactive, no AfterViewInit119 items = contentChildren(TabItemComponent); // ✅ Content query120 ```1211224. **Lifecycle hooks guidance:**123 - `OnInit` — fetch initial data, set up subscriptions (use `inject(DestroyRef)` for cleanup)124 - `OnDestroy` — manual cleanup only if `takeUntilDestroyed` or `DestroyRef` cannot be used125 - **Avoid `OnChanges`** — use signal inputs with `computed()` or `effect()` instead126127### Template Patterns1281291. **Use new control flow syntax** (Angular 17+) — `@for`, `@if`, `@switch`, `@defer`:130 ```html131 <!-- ✅ New control flow with track expression -->132 @for (task of tasks(); track task.id) {133 <app-task-card [task]="task" />134 } @empty {135 <p>No tasks found.</p>136 }137138 @if (isLoading()) {139 <app-spinner />140 } @else {141 <app-task-list [tasks]="tasks()" />142 }143144 @switch (task().priority) {145 @case ('high') { <span class="badge-high">High</span> }146 @case ('medium') { <span class="badge-med">Medium</span> }147 @default { <span class="badge-low">Low</span> }148 }149 ```1501512. **`@defer` for lazy-loaded template blocks:**152 ```html153 <!-- ✅ Lazy-load heavy component -->154 @defer (on viewport) {155 <app-task-analytics [tasks]="tasks()" />156 } @placeholder {157 <div class="skeleton" />158 }159 ```1601613. **Use `ng-container`** for grouping without extra DOM nodes — e.g., `<ng-container *ngTemplateOutlet="tpl" />`.1621634. **Avoid complex expressions in templates** — extract to `computed()`:164 ```typescript165 // ❌ template: `{{ tasks().filter(t => t.done).length }} / {{ tasks().length }}`166 // ✅ Extract to computed167 summary = computed(() => `${this.doneTasks().length} / ${this.tasks().length}`);168 ```169170### Dependency Injection1711721. **`inject()` function** over constructor injection in standalone components.1732. **Provide at appropriate level** — component, route, or root.1743. **Abstract services behind interfaces** for testability:175176```typescript177// ✅ Abstract class as interface (TypeScript has no runtime interfaces)178export abstract class TaskStorage {179 abstract getById(id: string): Observable<Task>;180 abstract save(task: Task): Observable<void>;181}182183// ✅ Implementation184@Injectable()185export class HttpTaskStorage extends TaskStorage {186 private readonly http = inject(HttpClient);187 getById(id: string) { return this.http.get<Task>(`/api/tasks/${id}`); }188 save(task: Task) { return this.http.post<void>('/api/tasks', task); }189}190191// ✅ Wired at route or root level192providers: [{ provide: TaskStorage, useClass: HttpTaskStorage }]193```194195### Reactive Forms1961971. **Reactive forms over template-driven** for complex forms.1982. **Typed forms** (`FormControl<string>`) — always.1993. **Custom validators** as pure functions:200201```typescript202// ✅ Typed form group with nonNullable controls203export class TaskFormComponent {204 form = new FormGroup({205 title: new FormControl('', { nonNullable: true,206 validators: [Validators.required, Validators.maxLength(200)] }),207 priority: new FormControl<'low' | 'medium' | 'high'>('medium', { nonNullable: true }),208 });209}210```211212### Routing Patterns2132141. **Functional guards** (Angular 15+) — no class-based guards:215 ```typescript216 // ✅ Functional guard217 export const authGuard: CanActivateFn = (route, state) => {218 const auth = inject(AuthService);219 return auth.isAuthenticated() || inject(Router).createUrlTree(['/login']);220 };221222 // ❌ Class-based guard — deprecated223 @Injectable() export class AuthGuard implements CanActivate { ... }224 ```2252262. **Functional resolvers** — same pattern, use `ResolveFn<T>`:227 ```typescript228 export const taskResolver: ResolveFn<Task> = (route) =>229 inject(TaskService).getById(route.paramMap.get('id')!);230 ```2312323. **Lazy loading with `loadChildren`** for feature routes:233 ```typescript234 {235 path: 'tasks',236 loadChildren: () => import('./features/task/task.routes')237 .then(m => m.TASK_ROUTES),238 canActivate: [authGuard],239 }240 ```2412424. **Route parameter binding with `input()`** (Angular 16+):243 ```typescript244 // In app.config.ts: withComponentInputBinding()245 // ✅ Route params bound as signal inputs — no ActivatedRoute needed246 taskId = input.required<string>();247248 // ❌ Manual route param subscription249 this.route.paramMap.pipe(...).subscribe(...)250 ```251252### State Management2532541. **Component signals first** — sufficient for most local UI state.2552. **NgRx Signal Store** for shared or complex state beyond a single component:256257 ```typescript258 // ✅ NgRx Signal Store259 export const TaskStore = signalStore(260 { providedIn: 'root' },261 withState<TaskState>({ tasks: [], isLoading: false, error: null }),262 withComputed(({ tasks }) => ({263 completedTasks: computed(() => tasks().filter(t => t.done)),264 })),265 withMethods((store, taskService = inject(TaskService)) => ({266 async loadTasks(): Promise<void> {267 patchState(store, { isLoading: true });268 const tasks = await firstValueFrom(taskService.getAll());269 patchState(store, { tasks, isLoading: false });270 },271 })),272 );273 ```2742753. **When to use what:**276 - **`signal()`** — local component state, simple parent-child data flow277 - **NgRx Signal Store** — shared state across components, entity management (`withEntities()`)278 - **RxJS + services** — real-time streams, WebSocket data, complex async orchestration279280### Error Handling281282> For universal error handling principles, see `.agents/rules/error-handling-principles.md`. Below: Angular-specific patterns only.2832841. **Global error handler** for uncaught exceptions:285 ```typescript286 @Injectable()287 export class GlobalErrorHandler implements ErrorHandler {288 handleError(error: unknown): void {289 this.logger.error('unhandled_error', { error }); // Log to observability platform290 }291 }292 ```2932942. **HTTP interceptor** for centralized error handling:295 ```typescript296 export const errorInterceptor: HttpInterceptorFn = (req, next) =>297 next(req).pipe(298 catchError((error: HttpErrorResponse) => {299 if (error.status === 401) {300 // Redirect to login301 }302 return throwError(() => error);303 })304 );305 ```3063073. **RxJS error handling** — never leave Observables unhandled. Always use `catchError` in `.pipe()` or handle in `subscribe()` error callback.308309### Anti-Patterns310311- ❌ **NgModules for new components** — use standalone components (default since v19)312- ❌ **BehaviorSubject for simple component state** — use signals313- ❌ **Constructor injection in standalone components** — use `inject()`314- ❌ **Manual subscriptions without cleanup** — use `takeUntilDestroyed()` or `async` pipe315- ❌ **`any` in template bindings** — type everything316- ❌ **Direct DOM manipulation** — use Angular's renderer or signals317- ❌ **`subscribe()` in components without unsubscribe** — prefer `async` pipe or `toSignal()`318- ❌ **`ChangeDetectionStrategy.Default`** without justification — always `OnPush`319- ❌ **`*ngFor` / `*ngIf` in new code** — use `@for` / `@if` control flow320- ❌ **Class-based guards and resolvers** — use functional equivalents321322```typescript323// ❌ Memory leak — subscription never cleaned up324ngOnInit() {325 this.taskService.getTasks().subscribe(tasks => this.tasks = tasks);326}327328// ✅ Auto-cleanup with takeUntilDestroyed329private destroyRef = inject(DestroyRef);330ngOnInit() {331 this.taskService.getTasks().pipe(332 takeUntilDestroyed(this.destroyRef)333 ).subscribe(tasks => this.tasks.set(tasks));334}335336// ✅ Even better — convert to signal337tasks = toSignal(this.taskService.getTasks(), { initialValue: [] });338```339340### Naming Conventions3413421. **File naming** — dot-separated with type suffix:343 - `task-list.component.ts`, `task.service.ts`, `task.pipe.ts`, `task.guard.ts`, `task.directive.ts`344 - `task.routes.ts` for feature route definitions345 - `task-list.component.spec.ts` for tests (co-located)3463472. **Selector prefixes** — use `app-` (or project-specific prefix from `angular.json`): `selector: 'app-task-card'`3483493. **Class naming** — suffix matches file type: `TaskListComponent`, `TaskService`, `HighlightDirective`, `DateFormatPipe`3503514. **Route file exports** — `UPPER_SNAKE_CASE`: `export const TASK_ROUTES: Routes = [...]`352353### Testing354355> For universal testing principles, see `.agents/rules/testing-strategy.md`. Below: Angular-specific patterns only.356> Test-file naming: `*.spec.ts` co-located (Angular CLI default — `.component.spec.ts` beside `.component.ts`). For the cross-framework reconciliation rule, see `@.agents/skills/typescript-idioms/references/project-structure.md` §Test Organization.3573581. **Angular Testing Library** for component tests (preferred over TestBed):359 ```typescript360 import { render, screen } from '@testing-library/angular';361362 it('should display task title', async () => {363 await render(TaskCardComponent, {364 componentInputs: { task: mockTask },365 });366 expect(screen.getByText('Deploy fix')).toBeInTheDocument();367 });368 ```3693702. **Spectator** for service tests:371 ```typescript372 const spectator = createServiceFactory({373 service: TaskService,374 mocks: [TaskStorage],375 });376 ```3773783. **`HttpTestingController`** for HTTP service tests — no live backend.3793804. **Signal Store testing** — test store methods directly, assert signal values:381 ```typescript382 it('should load tasks', async () => {383 const store = TestBed.inject(TaskStore);384 await store.loadTasks();385 expect(store.tasks().length).toBeGreaterThan(0);386 });387 ```388389### Formatting and Static Analysis390391| Tool | Purpose | Command |392|---|---|---|393| Prettier | Formatting | `npx prettier --write .` |394| ESLint + angular-eslint | Linting | `npx ng lint` |395| `strict` mode | Type checking | `"strict": true` in tsconfig.json |396| Angular compiler | Template checking | `npx ng build` (checks templates) |397398### Related399- Code Idioms and Conventions @.agents/rules/code-idioms-and-conventions.md400- TypeScript Idioms @.agents/skills/typescript-idioms/SKILL.md401- Angular Project Structure @.agents/skills/angular-idioms/references/project-structure.md402- Frontend Layout (framework-neutral, shared with React/Vue) @.agents/skills/frontend-design/references/frontend-layout.md403- Frontend Design @.agents/skills/frontend-design/SKILL.md404- Security Principles @.agents/rules/security-principles.md405- Accessibility Principles @.agents/rules/accessibility-principles.md406- Testing Strategy @.agents/rules/testing-strategy.md407- Error Handling Principles @.agents/rules/error-handling-principles.md408- Logging and Observability @.agents/rules/logging-and-observability-mandate.md409- Architectural Patterns @.agents/rules/architectural-pattern.md