5. Reactive Patterns in Angular

Subjects, async pipe, OnPush, and fully reactive component architecture

You've seen Observables, operators, and services. Now it's time to wire them together into a reactive component architecture — one where data flows through Observables from source to template, change detection is efficient, and there are no manual subscriptions to manage.

The Subject Family

Subjects are the bridge between imperative code (event handlers, lifecycle hooks) and the reactive world. A Subject is both an Observable and an Observer — you can push values into it with next() and subscribe to it like any Observable.

Subject — basic multicast

import { Subject } from 'rxjs';

const subject = new Subject<string>();

subject.subscribe(val => console.log('A:', val));
subject.subscribe(val => console.log('B:', val));

subject.next('hello');
// A: hello
// B: hello

subject.next('world');
// A: world
// B: world

Both subscribers receive every value. Unlike a cold Observable, there's one shared execution.

BehaviorSubject — has a current value

A BehaviorSubject requires an initial value and always holds a "current" value. New subscribers immediately receive the latest value upon subscribing.

import { BehaviorSubject } from 'rxjs';

const state$ = new BehaviorSubject<number>(0);

state$.subscribe(val => console.log('A:', val));
// A: 0  (immediately receives initial value)

state$.next(1);
// A: 1

state$.subscribe(val => console.log('B:', val));
// B: 1  (immediately receives current value)

state$.next(2);
// A: 2
// B: 2

console.log('current:', state$.getValue());
// current: 2

This is the most-used Subject in Angular. It's perfect for representing state that always has a value — the current user, a list of items, a filter selection.

ReplaySubject — replay N previous values

import { ReplaySubject } from 'rxjs';

const replay$ = new ReplaySubject<string>(2);  // buffer size of 2

replay$.next('a');
replay$.next('b');
replay$.next('c');

replay$.subscribe(val => console.log(val));
// b  (replays last 2)
// c

Use ReplaySubject(1) when you want BehaviorSubject behavior but don't have an initial value.

AsyncSubject — emit only the last value, on complete

import { AsyncSubject } from 'rxjs';

const async$ = new AsyncSubject<number>();
async$.next(1);
async$.next(2);
async$.next(3);
async$.complete();

async$.subscribe(val => console.log(val));
// 3  (only the last value, emitted on complete)

Rarely used directly, but it's how Angular's HttpClient works internally — one request, one response, then complete.

Choosing the right Subject

TypeInitial value?New subscriber getsUse for
SubjectNoNothing until next emissionEvents, actions
BehaviorSubjectYes (required)Current value immediatelyState, settings
ReplaySubject(n)NoLast n valuesLate subscribers needing history
AsyncSubjectNoOnly final value, after completeOne-shot async results

Try It Yourself — Subject Explorer

Pick a Subject type, then emit values and add subscribers in any order. Watch how each Subject type handles late subscribers differently. Try: emit a few values, then add a subscriber — what do they get?

The async Pipe — Subscribe in the Template

The async pipe is Angular's killer feature for reactive programming. It subscribes to an Observable, renders the latest value, and automatically unsubscribes when the component is destroyed.

Before: manual subscribe

@Component({
  template: `<div *ngFor="let user of users">{{ user.name }}</div>`
})
export class UserListComponent implements OnInit, OnDestroy {
  users: User[] = [];
  private sub: Subscription;

  constructor(private userService: UserService) {}

  ngOnInit() {
    this.sub = this.userService.getAll().subscribe(users => {
      this.users = users;
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();  // easy to forget!
  }
}

After: async pipe

@Component({
  template: `<div *ngFor="let user of users$ | async">{{ user.name }}</div>`
})
export class UserListComponent {
  users$ = inject(UserService).getAll();
}

That's it. No subscribe, no unsubscribe, no OnDestroy. The component went from 20 lines to 4.

Multiple async pipes with *ngIf

When you have multiple Observables, use *ngIf with an alias to avoid multiple subscriptions:

@Component({
  template: `
    <ng-container *ngIf="{
      users: users$ | async,
      loading: loading$ | async,
      error: error$ | async
    } as vm">
      <div *ngIf="vm.loading" class="spinner">Loading...</div>
      <div *ngIf="vm.error" class="error">{{ vm.error }}</div>
      <div *ngIf="vm.users" class="list">
        <div *ngFor="let user of vm.users">{{ user.name }}</div>
      </div>
    </ng-container>
  `
})
export class UserListComponent {
  private userService = inject(UserService);

  users$ = this.userService.getAll().pipe(
    catchError(err => {
      this.errorSubject.next(err.message);
      return of(null);
    })
  );
  private errorSubject = new Subject<string>();
  error$ = this.errorSubject.asObservable();
  loading$ = this.users$.pipe(
    map(() => false),
    startWith(true)
  );
}

The vm (view model) pattern gives your template a single object with all the data it needs, and each Observable is subscribed to exactly once.

OnPush Change Detection

By default, Angular checks every component in the tree on every event, timer, or HTTP response. With OnPush, Angular only checks a component when:

  1. An @Input() reference changes
  2. An event handler in the component fires
  3. An Observable piped through async emits a new value
  4. You manually call ChangeDetectorRef.markForCheck()
@Component({
  selector: 'app-user-card',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="card">
      <h3>{{ user.name }}</h3>
      <p>{{ user.email }}</p>
    </div>
  `
})
export class UserCardComponent {
  @Input() user: User;
}

With OnPush, this component is only re-rendered when a new user object is passed in (reference equality). Mutating user.name in place won't trigger a re-render — you need to create a new object.

OnPush + async pipe = peak performance

@Component({
  selector: 'app-user-list',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <app-user-card
      *ngFor="let user of users$ | async; trackBy: trackById"
      [user]="user">
    </app-user-card>
  `
})
export class UserListComponent {
  users$ = inject(UserService).getAll();

  trackById(_: number, user: User) {
    return user.id;
  }
}

The async pipe tells Angular "this component's data changed" only when the Observable emits. Combined with OnPush, Angular skips this component entirely during change detection cycles where nothing changed. In large apps, this is a major performance win.

Default OnPush App Nav Main Footer List Detail All 6 checked every cycle App Nav Main Footer List Detail data$ | async Only 3 checked when data$ emits

Reactive Component Patterns

Pattern 1: Derived state with computed Observables

Instead of storing derived values, compute them from source Observables:

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <input [formControl]="searchControl">
    <p>Showing {{ (filteredCount$ | async) }} of {{ (totalCount$ | async) }} items</p>
    <div *ngFor="let item of filteredItems$ | async">{{ item.name }}</div>
  `
})
export class ItemListComponent {
  searchControl = new FormControl('');
  private items$ = inject(ItemService).getAll().pipe(shareReplay(1));

  filteredItems$ = combineLatest([
    this.items$,
    this.searchControl.valueChanges.pipe(startWith(''))
  ]).pipe(
    map(([items, search]) =>
      items.filter(item =>
        item.name.toLowerCase().includes(search.toLowerCase())
      )
    )
  );

  totalCount$ = this.items$.pipe(map(items => items.length));
  filteredCount$ = this.filteredItems$.pipe(map(items => items.length));
}

No imperative state tracking. The filtered list, total count, and filtered count are all derived from the source data and the search control. Change the search term, and everything updates automatically.

Pattern 2: Action streams for user interactions

Convert imperative events into Observables, then combine them:

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <button (click)="sort$.next('name')">Sort by Name</button>
    <button (click)="sort$.next('date')">Sort by Date</button>
    <button (click)="refresh$.next()">Refresh</button>

    <div *ngFor="let item of items$ | async">
      {{ item.name }} — {{ item.date | date }}
    </div>
  `
})
export class SortableListComponent {
  sort$ = new BehaviorSubject<'name' | 'date'>('name');
  refresh$ = new Subject<void>();

  items$ = this.refresh$.pipe(
    startWith(undefined),
    switchMap(() => inject(ItemService).getAll()),
    combineLatestWith(this.sort$),
    map(([items, sortBy]) =>
      [...items].sort((a, b) =>
        sortBy === 'date'
          ? new Date(b.date).getTime() - new Date(a.date).getTime()
          : a.name.localeCompare(b.name)
      )
    )
  );
}

Button clicks are modeled as stream emissions. The data pipeline reacts to both refresh triggers and sort changes.

Pattern 3: Loading and error states

A reusable pattern for tracking async state:

interface AsyncState<T> {
  data: T | null;
  loading: boolean;
  error: string | null;
}

function toAsyncState<T>(): OperatorFunction<T, AsyncState<T>> {
  return (source$) => source$.pipe(
    map(data => ({ data, loading: false, error: null })),
    startWith({ data: null, loading: true, error: null }),
    catchError(err => of({ data: null, loading: false, error: err.message }))
  );
}

// Usage:
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <ng-container *ngIf="state$ | async as state">
      <div *ngIf="state.loading">Loading...</div>
      <div *ngIf="state.error" class="error">{{ state.error }}</div>
      <div *ngIf="state.data as users">
        <div *ngFor="let user of users">{{ user.name }}</div>
      </div>
    </ng-container>
  `
})
export class UserListComponent {
  state$ = inject(UserService).getAll().pipe(toAsyncState());
}

The toAsyncState operator wraps any Observable into a stream of { data, loading, error } objects. The template can react to each state cleanly.

Signals: The Future of Reactivity in Angular

Angular 16+ introduced Signals — a synchronous reactivity primitive that complements Observables. Signals are simpler for synchronous state, while Observables remain the right choice for async operations and event streams.

import { signal, computed } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';

@Component({
  template: `
    <input (input)="onSearch($event)">
    <p>Showing {{ filteredCount() }} of {{ users().length }} users</p>
    <div *ngFor="let user of filteredUsers()">{{ user.name }}</div>
  `
})
export class UserListComponent {
  private userService = inject(UserService);

  // Convert Observable to Signal
  users = toSignal(this.userService.getAll(), { initialValue: [] });

  // Synchronous reactive state
  searchTerm = signal('');

  // Computed (derived) state
  filteredUsers = computed(() =>
    this.users().filter(u =>
      u.name.toLowerCase().includes(this.searchTerm().toLowerCase())
    )
  );
  filteredCount = computed(() => this.filteredUsers().length);

  onSearch(event: Event) {
    this.searchTerm.set((event.target as HTMLInputElement).value);
  }
}

toSignal bridges the Observable world to the Signal world. Use Observables for HTTP, WebSockets, route changes, and complex async flows. Use Signals for component-local state and simple derived values.

The reverse bridge also exists:

import { toObservable } from '@angular/core/rxjs-interop';

const count = signal(0);
const count$ = toObservable(count);

count$.pipe(
  debounceTime(300),
  switchMap(n => this.http.get(`/api/page/${n}`))
).subscribe(data => { /* ... */ });

Putting It All Together: A Fully Reactive Component

Here's a complete, production-style component that uses everything from this article:

@Component({
  selector: 'app-product-catalog',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="filters">
      <input [formControl]="search" placeholder="Search products...">
      <select [formControl]="category">
        <option value="">All Categories</option>
        <option *ngFor="let cat of categories$ | async" [value]="cat.id">
          {{ cat.name }}
        </option>
      </select>
      <select [formControl]="sortBy">
        <option value="name">Name</option>
        <option value="price-asc">Price: Low to High</option>
        <option value="price-desc">Price: High to Low</option>
      </select>
    </div>

    <ng-container *ngIf="vm$ | async as vm">
      <p class="count">{{ vm.filtered.length }} products</p>

      <div class="grid">
        <app-product-card
          *ngFor="let product of vm.filtered; trackBy: trackById"
          [product]="product"
          (addToCart)="onAddToCart($event)">
        </app-product-card>
      </div>

      <p *ngIf="vm.filtered.length === 0" class="empty">
        No products match your filters.
      </p>
    </ng-container>
  `
})
export class ProductCatalogComponent {
  private productService = inject(ProductService);
  private cartService = inject(CartService);

  search = new FormControl('');
  category = new FormControl('');
  sortBy = new FormControl('name');

  categories$ = this.productService.getCategories();

  private products$ = this.productService.getAll().pipe(shareReplay(1));

  vm$ = combineLatest([
    this.products$,
    this.search.valueChanges.pipe(startWith(''), debounceTime(200)),
    this.category.valueChanges.pipe(startWith('')),
    this.sortBy.valueChanges.pipe(startWith('name'))
  ]).pipe(
    map(([products, search, category, sortBy]) => {
      let filtered = products;

      if (search) {
        const term = search.toLowerCase();
        filtered = filtered.filter(p =>
          p.name.toLowerCase().includes(term) ||
          p.description.toLowerCase().includes(term)
        );
      }

      if (category) {
        filtered = filtered.filter(p => p.categoryId === category);
      }

      switch (sortBy) {
        case 'price-asc':
          filtered = [...filtered].sort((a, b) => a.price - b.price);
          break;
        case 'price-desc':
          filtered = [...filtered].sort((a, b) => b.price - a.price);
          break;
        default:
          filtered = [...filtered].sort((a, b) => a.name.localeCompare(b.name));
      }

      return { filtered };
    })
  );

  trackById(_: number, product: Product) {
    return product.id;
  }

  onAddToCart(product: Product) {
    this.cartService.addItem(product);
  }
}

Zero manual subscriptions. Zero OnDestroy. Every piece of state is derived from Observable sources. Change detection is OnPush — Angular only re-renders when the data actually changes.

What's Next

This pattern of services holding state with BehaviorSubject works well for small-to-medium apps. But as your app grows — more state, more actions, more side effects — you need a more structured approach. The next article introduces NgRx — the Redux-inspired state management library for Angular, with its store, actions, reducers, selectors, and effects.