Angular signals patterns

From FerroxLabs/murage · View interactive version

Angular signals patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level angular signals patterns implementation: typescript and frameworks decision frameworks, production-ready patterns, and concrete templates for angular signals patterns workflows. Use when the user asks about angular signals patterns, angular signals patterns configuration, or type

How to use this skill

Skill file

Angular Signals Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Identify the Reactivity Scope and State Ownership

Before writing any signal code, classify what kind of state is being managed and where it lives.

2. Define the Signal Graph Structure

Design the signal dependency graph before implementation to avoid creating brittle or cyclical dependencies.

3. Implement Writable Signals with Correct Mutation Patterns

Signal mutations must be performed correctly to trigger reactivity and avoid stale references.

```typescript

// BAD: infers signal<never[]>

const items = signal([]);

// GOOD

const items = signal<Item[]>([]);

```

```typescript

items.update(prev => [...prev, newItem]); // append

items.update(prev => prev.filter(i => i.id !== id)); // remove

count.update(n => n + 1); // increment

```

```typescript

const config = signal<Config>(initialConfig, {

equal: (a, b) => JSON.stringify(a) === JSON.stringify(b)

});

```

Use JSON.stringify only for small, serializable objects. For large objects, write a structural comparator or use a library like fast-deep-equal.

4. Build Computed Signals for Derived State

computed() is the most powerful primitive for keeping derived state in sync without explicit subscription management.

```typescript

readonly filteredItems = computed(() =>

this.items().filter(item => item.active && item.category === this.selectedCategory())

);

readonly totalPrice = computed(() =>

this.cartItems().reduce((sum, item) => sum + item.price * item.quantity, 0)

);

```

5. Use `effect()` Correctly for Side Effects

effect() is the most commonly misused signal API. Apply it with discipline.

```typescript

effect(() => {

const value = this.externalSignal();

this.localSignal.set(processValue(value));

}, { allowSignalWrites: true });

```

This option exists to escape hatches, not as a default pattern. If you use it more than once per class, reconsider the design.

6. Wire Signal-Based Component Inputs and Outputs

Angular 17.1+ introduced signal-based input(), output(), and model() APIs that replace @Input(), @Output(), and @Input()/@Output() pairs.

```typescript

readonly userId = input.required<string>(); // throws if not provided

readonly pageSize = input<number>(25); // optional, defaults to 25

```

```typescript

readonly selectedDate = model<Date | null>(null);

// Parent binds with [(selectedDate)]="parentDate"

// Child updates with: this.selectedDate.set(newDate)

```

```typescript

readonly itemSelected = output<Item>();

// Emit with: this.itemSelected.emit(item)

```

7. Implement Signal-Based Service Stores

For feature or global state, implement a signal store as a plain injectable service or using NgRx SignalStore.

Hand-rolled signal store pattern:

@Injectable({ providedIn: 'root' })
export class CartStore {
  // Private writable signals -- only this store mutates state
  private readonly _items = signal<CartItem[]>([]);
  private readonly _status = signal<'idle' | 'loading' | 'error'>('idle');

  // Public read-only projections
  readonly items: Signal<CartItem[]> = this._items.asReadonly();
  readonly status: Signal<'idle' | 'loading' | 'error'> = this._status.asReadonly();

  // Computed selectors
  readonly totalItems = computed(() => this._items().reduce((sum, i) => sum + i.quantity, 0));
  readonly totalPrice = computed(() => this._items().reduce((sum, i) => sum + i.price * i.quantity, 0));
  readonly isEmpty = computed(() => this._items().length === 0);

  // Commands (methods that mutate state)
  addItem(item: CartItem): void {
    this._items.update(items => {
      const existing = items.find(i => i.productId === item.productId);
      if (existing) {
        return items.map(i => i.productId === item.productId
          ? { ...i, quantity: i.quantity + item.quantity }
          : i
        );
      }
      return [...items, item];
    });
  }

  removeItem(productId: string): void {
    this._items.update(items => items.filter(i => i.productId !== productId));
  }

  clearCart(): void {
    this._items.set([]);
  }
}

```typescript

loadItems(): void {

this._status.set('loading');

this.http.get<CartItem[]>('/api/cart').pipe(

takeUntilDestroyed(this.destroyRef)

).subscribe({

next: items => { this._items.set(items); this._status.set('idle'); },

error: () => this._status.set('error')

});

}

```

8. Integrate Signals with RxJS Using Interop APIs

Signals and Observables coexist in Angular -- know the correct bridge for each direction.

```typescript

readonly searchResults = toSignal(

this.searchQuery$.pipe(

debounceTime(300),

distinctUntilChanged(),

switchMap(query => this.searchService.search(query))

),

{ initialValue: [] } // avoids Signal<T | undefined>

);

```

Always provide initialValue unless the observable is guaranteed to emit synchronously, because toSignal() without initialValue creates Signal<T | undefined> and causes undefined-access errors in templates.

```typescript

readonly results$ = toObservable(this.searchQuery).pipe(

debounceTime(300),

switchMap(q => this.http.get<Result[]>(/api/search?q=${q}))

);

```

toObservable() uses effect() internally and emits on each signal change. It must be called in an injection context.

```typescript

readonly userResource = resource({

request: () => ({ id: this.userId() }),

loader: ({ request }) => fetch(/api/users/${request.id}).then(r => r.json())

});

// Access: this.userResource.value(), this.userResource.isLoading(), this.userResource.error()

```


Output Format

When advising on Angular Signals patterns, produce output in this structure:

## Signal Architecture Assessment

### State Classification
| State Slice       | Type         | Owner            | Pattern          |
|-------------------|--------------|------------------|------------------|
| [state name]      | local/shared/global | component/service/store | signal/computed/toSignal |

### Signal Graph Diagram (text representation)
[WritableSignal] --> [computed] --> [template binding]
                 --> [computed] --> [effect (side effect)]

### Implementation

#### Signal Definitions
// Writable signals with types
// Computed signals
// Effects (with justification)

#### Service Store (if applicable)
// Full store class with private writable, public readonly, computed selectors, command methods

#### Interop Layer (if mixing RxJS)
// toSignal() / toObservable() calls with options

### Migration Path (if replacing existing code)
Phase 1: [specific migration step -- which component or service to migrate first]
Phase 2: [next migration step]
Phase 3: [cleanup and removal of old patterns]

### Tradeoffs Accepted
- [specific tradeoff and why it is acceptable for this context]

Rules

  1. NEVER declare a signal() without an explicit TypeScript generic type annotation when the initial value could be misread by inference -- especially for null, undefined, empty arrays, and union types. Missing generics cause runtime undefined-access errors that TypeScript does not catch at compile time.
  1. NEVER write to a signal inside a computed() callback -- Angular's glitch-free algorithm prevents this, and attempting it throws a runtime error. If you find yourself wanting to, you need to restructure the graph so the writable signal is an input and the computed is the output.
  1. ALWAYS call effect() and toSignal() inside an injection context (constructor, field initializer, runInInjectionContext()). Calling them outside throws NG0203: inject() must be called from an injection context. This is the most common runtime error when adopting signals.
  1. NEVER expose a WritableSignal directly from a service -- always use .asReadonly() to return a Signal<T>. Components that can freely mutate service state break encapsulation and make bugs impossible to trace.
  1. ALWAYS provide initialValue to toSignal() unless the source Observable is guaranteed to emit synchronously (e.g., of(value), from([]), or a BehaviorSubject). Without initialValue, the resulting type is Signal<T | undefined> and templates will throw on first render.
  1. NEVER use effect() to synchronize two writable signals (keeping signalA updated whenever signalB changes). This is a computed() use case. Using effect() for this creates asynchronous update behavior that causes the UI to flash intermediate states.
  1. NEVER create signal-based stores with mutable public state properties. The pattern readonly items = signal<Item[]>([]) on a service is wrong because any injector can call .set() or .update(). Always private the writable signal and expose .asReadonly().
  1. ALWAYS unsubscribe or clean up toObservable() and manually created effect() calls in services. Services provided at root live for the application lifetime, but feature-scoped services may be destroyed. Use takeUntilDestroyed(this.destroyRef) on Observable chains derived from signals.
  1. NEVER mix @Input() decorator-based inputs with signal input() on the same component property. The two systems are not compatible for the same binding. Migrate the entire component's inputs at once to avoid confusing the Angular compiler and template type checker.
  1. ALWAYS prefer computed() over storing derived state in a writable signal. If you see a pattern where ngOnChanges or an effect() sets one signal based on another, that derived signal should be a computed(). Redundant writable signals for derived data become inconsistent when update paths are missed.
  1. NEVER use JSON.stringify as an equality comparator for signals that hold large objects or objects with circular references -- it is O(n) on every change detection cycle and will throw on circular structures. Write a structural comparator or use fast-deep-equal for complex objects.
  1. ALWAYS test computed signal logic in isolation using TestBed.runInInjectionContext() or by instantiating the store/service directly in unit tests. Angular's signal primitives work in test environments -- there is no need to mock them.

Edge Cases

Legacy RxJS-Heavy Codebase Migration

When introducing signals to a codebase built on BehaviorSubject + async pipe patterns, do not attempt to rewrite all reactive state at once.

Signals Inside `OnPush` Change Detection Components

Angular Signals are deeply integrated with the Zoneless / OnPush change detection model.

Signal Equality and Unnecessary Recomputation

Angular compares signal values with Object.is() by default. This causes issues with non-primitive values.

```typescript

const ids = signal<string[]>([], {

equal: (a, b) => a.length === b.length && a.every((v, i) => v === b[i])

});

```

Signals in Angular Route Resolvers and Guards

Route resolvers and guards in Angular 17+ can use signals via inject() and toSignal(), but with important constraints.

```typescript

export const authGuard = () => {

const authStore = inject(AuthStore);

return authStore.isAuthenticated() || router.createUrlTree(['/login']);

};

```

This works synchronously because isAuthenticated() reads a signal synchronously.

NgRx SignalStore Integration

NgRx SignalStore (introduced in NgRx 17) is the library-supported signal store pattern and has specific conventions.

Performance Degradation with Large Signal Graphs

When a single user action triggers updates across dozens of computed signals, the change detection overhead can become noticeable.

Testing Signal-Based Components and Services

Signal primitives work in TestBed, but there are testing patterns specific to signals.

```typescript

store.setItems([{ id: '1', active: true }, { id: '2', active: false }]);

expect(store.activeItems()).toHaveLength(1);

```


Example

Input: "I'm building an e-commerce product listing page in Angular 17. I have a ProductService that fetches products via HTTP. The page has search, category filter, sort, and pagination. Multiple child components display the filtered results, loading state, and pagination controls. What's the correct signals architecture?"

Output:

Signal Architecture Assessment

State Classification

| State Slice | Type | Owner | Pattern |

|---|---|---|---|

| searchQuery | local UI state | ProductListStore | signal<string>('') |

| selectedCategory | local UI state | ProductListStore | signal<string \| null>(null) |

| sortOrder | local UI state | ProductListStore | signal<SortOrder>('relevance') |

| currentPage | local UI state | ProductListStore | signal<number>(1) |

| rawProducts | server data | ProductListStore | toSignal(http$, { initialValue: [] }) |

| filteredProducts | derived | ProductListStore | computed() |

| totalPages | derived | ProductListStore | computed() |

| isLoading | derived from Observable | ProductListStore | signal<boolean>(false) |

| error | derived from Observable | ProductListStore | signal<string \| null>(null) |

Signal Graph

searchQuery ──────┐
selectedCategory ─┼──> [filterParams: computed] ──> HTTP trigger (toObservable)
sortOrder ────────┤                                       │
currentPage ──────┘                                  rawProducts (toSignal)
                                                          │
                                              filteredProducts (computed)
                                                          │
                                              ┌───────────┴────────────┐
                                        template bindings         totalPages (computed)
                                        (product-grid, pagination)

Implementation

// product-list.store.ts
import { Injectable, computed, signal, inject } from '@angular/core';
import { toSignal, toObservable } from '@angular/core/rxjs-interop';
import { switchMap, catchError, tap, debounceTime, distinctUntilChanged } from 'rxjs/operators';
import { of } from 'rxjs';
import { HttpClient } from '@angular/common/http';

export type SortOrder = 'relevance' | 'price-asc' | 'price-desc' | 'newest';

interface FilterParams {
  query: string;
  category: string | null;
  sort: SortOrder;
  page: number;
}

export interface Product {
  id: string;
  name: string;
  price: number;
  category: string;
  imageUrl: string;
}

@Injectable()  // NOT providedIn: 'root' -- scoped to the feature route
export class ProductListStore {
  private readonly http = inject(HttpClient);

  // ── Writable source signals (private -- only this store mutates them) ──
  private readonly _searchQuery = signal<string>('');
  private readonly _selectedCategory = signal<string | null>(null);
  private readonly _sortOrder = signal<SortOrder>('relevance');
  private readonly _currentPage = signal<number>(1);
  private readonly _isLoading = signal<boolean>(false);
  private readonly _error = signal<string | null>(null);

  // ── Public read-only projections ──
  readonly searchQuery = this._searchQuery.asReadonly();
  readonly selectedCategory = this._selectedCategory.asReadonly();
  readonly sortOrder = this._sortOrder.asReadonly();
  readonly currentPage = this._currentPage.asReadonly();
  readonly isLoading = this._isLoading.asReadonly();
  readonly error = this._error.asReadonly();

  // ── Computed filter params (collapses 4 signals into one fetch trigger) ──
  private readonly filterParams = computed<FilterParams>(() => ({
    query: this._searchQuery(),
    category: this._selectedCategory(),
    sort: this._sortOrder(),
    page: this._currentPage(),
  }));

  // ── HTTP trigger: filterParams Observable drives product fetching ──
  // toObservable converts the computed signal into a stream
  // debounceTime(300) prevents fetching on every keystroke
  private readonly products$ = toObservable(this.filterParams).pipe(
    debounceTime(300),
    distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)),
    tap(() => {
      this._isLoading.set(true);
      this._error.set(null);
    }),
    switchMap(params =>
      this.http.get<{ products: Product[]; total: number }>(
        '/api/products',
        { params: this.buildHttpParams(params) }
      ).pipe(
        catchError(err => {
          this._error.set('Failed to load products. Please try again.');
          this._isLoading.set(false);
          return of({ products: [], total: 0 });
        })
      )
    ),
    tap(() => this._isLoading.set(false))
  );

  // ── Convert HTTP Observable to a signal for template consumption ──
  private readonly productResponse = toSignal(
    this.products$,
    { initialValue: { products: [], total: 0 } }
  );

  // ── Public computed selectors ──
  readonly products = computed(() => this.productResponse().products);
  readonly totalResults = computed(() => this.productResponse().total);
  readonly totalPages = computed(() => Math.ceil(this.totalResults() / 24));  // 24 per page
  readonly hasResults = computed(() => this.products().length > 0);
  readonly isEmpty = computed(() =>
    !this.isLoading() && !this.error() && !this.hasResults()
  );

  // ── Commands (state mutation methods) ──
  setSearchQuery(query: string): void {
    this._searchQuery.set(query.trim());
    this._currentPage.set(1);  // reset pagination on search change
  }

  setCategory(category: string | null): void {
    this._selectedCategory.set(category);
    this._currentPage.set(1);
  }

  setSortOrder(sort: SortOrder): void {
    this._sortOrder.set(sort);
    this._currentPage.set(1);
  }

  goToPage(page: number): void {
    const total = this.totalPages();
    if (page < 1 || page > total) return;  // guard invalid page numbers
    this._currentPage.set(page);
  }

  private buildHttpParams(params: FilterParams): Record<string, string> {
    const result: Record<string, string> = {
      q: params.query,
      sort: params.sort,
      page: String(params.page),
      pageSize: '24',
    };
    if (params.category) result['category'] = params.category;
    return result;
  }
}
// product-list.component.ts
import { Component, inject, ChangeDetectionStrategy } from '@angular/core';
import { ProductListStore, SortOrder } from './product-list.store';

@Component({
  selector: 'app-product-list',
  standalone: true,
  changeDetection: ChangeDetectionStrategy.OnPush,  // signals work with OnPush
  providers: [ProductListStore],                     // feature-scoped -- one instance per route
  template: `
    <app-search-bar
      [value]="store.searchQuery()"
      (search)="store.setSearchQuery($event)"
    />
    <app-category-filter
      [selected]="store.selectedCategory()"
      (categoryChange)="store.setCategory($event)"
    />
    <app-sort-selector
      [current]="store.sortOrder()"
      (sortChange)="store.setSortOrder($event)"
    />

    @if (store.isLoading()) {
      <app-loading-skeleton [rows]="8" />
    } @else if (store.error()) {
      <app-error-message [message]="store.error()!" />
    } @else if (store.isEmpty()) {
      <app-empty-state [query]="store.searchQuery()" />
    } @else {
      <app-product-grid [products]="store.products()" />
      <app-pagination
        [currentPage]="store.currentPage()"
        [totalPages]="store.totalPages()"
        (pageChange)="store.goToPage($event)"
      />
      <p class="results-count">{{ store.totalResults() }} results</p>
    }
  `
})
export class ProductListComponent {
  readonly store = inject(ProductListStore);
}
// product-list.store.spec.ts
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ProductListStore } from './product-list.store';

describe('ProductListStore', () => {
  let store: ProductListStore;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ProductListStore],
    });
    store = TestBed.inject(ProductListStore);
    httpMock = TestBed.inject(HttpTestingController);
  });

  it('should reset to page 1 when search query changes', () => {
    store.goToPage(3);
    expect(store.currentPage()).toBe(3);

    store.setSearchQuery('shoes');
    expect(store.currentPage()).toBe(1);
    expect(store.searchQuery()).toBe('shoes');
  });

  it('should compute isEmpty correctly', () => {
    // Before any HTTP response, isLoading is true, so isEmpty should be false
    expect(store.isEmpty()).toBe(false);
  });
});

Migration Path (from existing BehaviorSubject-based component)

Phase 1 (Week 1): Add ProductListStore service alongside the existing component. Do not change the existing component yet. Validate the store logic in isolation with unit tests.

Phase 2 (Week 2): Replace the existing component's template with signal-based bindings, using toSignal() to bridge any remaining Observable dependencies from parent services that have not yet been migrated.

Phase 3 (Week 3): Remove the old BehaviorSubject properties and async pipes from the component. Remove ngOnInit Observable subscriptions. Delete the old manual subscription teardown logic in ngOnDestroy.

Tradeoffs Accepted

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.