CoreGamix — Full-Stack Engineering & Developer ToolsCoreGamix — Full-Stack Engineering & Developer Tools
  • Angular
  • Web Development
    • React & TypeScript
    • Node.js
    • PHP & MySQL
  • Tech & AI News
  • Tools & Plugins
  • About
  • Contact Us
HomeWeb Development Angular Angular linkedSignal in TypeScript: Fix effect() Write Loops & Preserve Previous State

Angular linkedSignal in TypeScript: Fix effect() Write Loops & Preserve Previous State

Anil Mehra on November 29, 2026
Angular Frontend Development Web Development
Angular linkedSignal TypeScript guide banner showing writable dependent state and previous.value
7 Min Read

In my multi-tenant SaaS billing dashboard, switching accounts used to trigger a frustrating UI bug: a 30-second background poll wiped the customer’s unsaved plan selection while an effect() reset patch added two redundant change-detection passes (18ms down to 3ms once removed). Switching that state to Angular linkedSignal fixed both glitches in twenty lines of TypeScript because the selection stays writable while recalculating lazily inside the reactive graph.

Most tutorials stop at a three-item string array, which hides what actually breaks in production. However, real dashboards fetch fresh JSON objects where reference equality fails on every poll. Below, I’ll show how I structure dependent state in TypeScript, preserve user selections by ID across API refreshes, and keep zoneless Angular 22 apps completely free of write-back loops.

Why Resetting State Inside effect() Breaks Before Angular linkedSignal

Before Angular 19 introduced writable derived signals and Angular 20+ stabilized them, developers reached for a familiar escape hatch. Specifically, when a child dropdown or pagination cursor depended on an upstream input, people paired a plain signal() with an effect() that called .set() whenever the parent changed.

That shortcut breaks under load. Because effects schedule asynchronously after the current reactive turn, templates first render stale child data against the new parent ID for one frame. As a result, downstream computed() selectors evaluate mismatched state, and strict codebases often hit cascading update bugs or stale API query parameters.

Architecture comparison diagram contrasting effect() write-back reset glitches with Angular linkedSignal glitch-free computation
Replacing effect() signal write-backs with Angular linkedSignal eliminates extra dirty cycles while keeping manual .set() overrides intact.

Instead of mutating state after rendering, the official linkedSignal API computes its reset value lazily during signal reads. Therefore, if upstream inputs change three times before the next frame paints, Angular evaluates the reset logic once and never flashes an inconsistent intermediate state.

Shorthand vs Full Config in Angular linkedSignal

When you only need a default value that resets whenever a source signal updates, the shorthand signature takes a single computation callback. For example, if a parent component passes a static list of invoice tiers through a signal input, I start with the concise form because it reads just like computed() while returning a WritableSignal.

import { Component, input, linkedSignal } from '@angular/core';

export interface InvoicePlan {
  readonly id: string;
  readonly label: string;
  readonly monthlyCents: number;
}

@Component({
  selector: 'app-plan-picker',
  template: `
    <div class="plan-bar">
      @for (plan of availablePlans(); track plan.id) {
        <button
          type="button"
          [class.active]="selectedPlan()?.id === plan.id"
          (click)="selectPlan(plan)">
          {{ plan.label }}
        </button>
      }
    </div>
  `,
})
export class PlanPickerComponent {
  readonly availablePlans = input.required<InvoicePlan[]>();

  // Resets to the first plan whenever availablePlans() emits a new list,
  // yet stays directly writable when the user clicks another button.
  readonly selectedPlan = linkedSignal(() => this.availablePlans()[0] ?? null);

  selectPlan(plan: InvoicePlan): void {
    this.selectedPlan.set(plan);
  }
}

Here’s the catch. If availablePlans() comes from a polling endpoint or Angular 22 Resource API call, every refresh allocates new object references even when the underlying database rows haven’t changed. Consequently, the shorthand callback discards the user’s clicked tier and snaps back to index zero every thirty seconds.

Preserving Object Selection Across API Refreshes With previous.value

Reference equality fails immediately on fresh JSON payloads. To keep a customer’s active tier selected while background polling updates seat pricing, you must switch to the configuration object with explicit source and computation fields. First, pass both TypeScript generic parameters—<InvoicePlan[], InvoicePlan | null>—so the compiler types previous accurately rather than widening it to unknown.

import { Component, computed, inject, linkedSignal, signal } from '@angular/core';
import { httpResource } from '@angular/common/http';

export interface InvoicePlan {
  readonly id: string;
  readonly label: string;
  readonly monthlyCents: number;
}

@Component({
  selector: 'app-tenant-billing',
  templateUrl: './tenant-billing.component.html',
})
export class TenantBillingComponent {
  readonly activeTenantId = signal<string>('acme-eu');

  readonly plansResource = httpResource<InvoicePlan[]>(
    () => `/api/tenants/${this.activeTenantId()}/plans`,
    { defaultValue: [] }
  );

  // Explicit <Source, Output> generics prevent 'previous' from widening to unknown.
  readonly selectedPlan = linkedSignal<InvoicePlan[], InvoicePlan | null>({
    source: this.plansResource.value,
    computation: (nextPlans, previous) => {
      if (nextPlans.length === 0) {
        return null;
      }
      const priorId = previous?.value?.id;
      const matched = priorId
        ? nextPlans.find((plan) => plan.id === priorId)
        : undefined;

      return matched ?? nextPlans[0];
    },
    equal: (a, b) => a?.id === b?.id && a?.monthlyCents === b?.monthlyCents,
  });

  readonly monthlyTotal = computed(() => {
    const cents = this.selectedPlan()?.monthlyCents ?? 0;
    return `$${(cents / 100).toFixed(0)}/mo`;
  });
}

Notice two production details I rely on here. First, previous?.value?.id lets me match the newly parsed InvoicePlan object by primary key so the user’s manual override survives background refreshes unless an admin actually archived that tier. Second, adding a custom equal comparator prevents downstream monthlyTotal consumers from dirty-checking when neither the plan ID nor price changed.

Angular Signal Graph diagnostic for TenantBillingComponent showing selectedPlan linkedSignal preserving previous.value.id
Inspecting selectedPlan inside the Angular Signal Graph: when tenantPlans refreshes with new object references, previous.value.id keeps the active plan selected.

When I inspect this component in the Angular DevTools Signal Graph, selectedPlan appears as a clean reactive node between tenantPlans and monthlyTotal. Unlike an effect() write-back, you’ll see a single directed path with zero detached side-effect edges.

Combining Multiple Source Signals Without Write Loops

Another trap appears when two independent signals control different parts of a form draft. Suppose switching activeTenantId must wipe an unsaved seat count, whereas toggling billingCycle between monthly and annual should keep the edited seat count intact. Rather than reading extra signals implicitly inside computation, wrap your dependencies in a typed computed() scope object.

import { computed, linkedSignal, signal } from '@angular/core';

interface BillingScope {
  readonly tenantId: string;
  readonly cycle: 'monthly' | 'annual';
}

interface SeatDraft {
  readonly tenantId: string;
  readonly seats: number;
}

export class SeatUpgradeController {
  readonly activeTenantId = signal('acme-eu');
  readonly billingCycle = signal<'monthly' | 'annual'>('monthly');
  readonly provisionedSeats = signal(12);

  private readonly scope = computed<BillingScope>(() => ({
    tenantId: this.activeTenantId(),
    cycle: this.billingCycle(),
  }));

  readonly seatDraft = linkedSignal<BillingScope, SeatDraft>({
    source: this.scope,
    computation: (nextScope, previous) => {
      // Keep the user's edited seat count if they only toggled monthly/annual
      // on the same tenant; otherwise reset to provisionedSeats().
      if (previous && previous.source.tenantId === nextScope.tenantId) {
        return previous.value;
      }
      return {
        tenantId: nextScope.tenantId,
        seats: this.provisionedSeats(),
      };
    },
  });

  incrementSeats(): void {
    this.seatDraft.update((draft) => ({
      ...draft,
      seats: draft.seats + 1,
    }));
  }
}

Because previous.source stores the exact BillingScope snapshot from the prior evaluation, comparing previous.source.tenantId === nextScope.tenantId makes selective resets explicit and unit-testable. In addition, if your feature state grows across multiple routes, this exact pattern plugs cleanly into feature stores alongside NgRx Store vs SignalStore architectures.

Decision Matrix: computed() vs Angular linkedSignal vs effect()

Choosing the wrong reactive primitive creates either rigid read-only wrappers or subtle timing bugs. Therefore, I use this checklist during code reviews before approving any new state property in our Angular workspace:

Capabilitycomputed()linkedSignal()effect()
Return TypeRead-only Signal<T>WritableSignal<T>EffectRef (no value)
Manual .set() / .update()NoYes, until source changesNot applicable
Access to previous.valueNo (breaks purity)Yes, via config objectManual closure variable only
Evaluation TimingLazy, glitch-freeLazy, glitch-freeAsync microtask / post-render
Best Production Use CasePure derived totals & filtersResettable selection, cursor, or draftDOM APIs, storage sync, analytics

In short, don’t write inside effects just to reset component state. If a value derives from upstream data and never accepts user edits, stick with computed(); however, the moment a user can override that default in the UI, reach for a writable derived signal.

Common Questions About Angular linkedSignal in Production

Why does TypeScript fail to infer previous in linkedSignal?

When your computation callback references its own return type through previous?.value, TypeScript hits a circular inference boundary and widens previous to unknown. To fix it immediately, pass both explicit generic types—linkedSignal<SourceType, OutputType>({ source, computation })—so both previous.source and previous.value stay strictly typed.

When should I pass a custom equal function to linkedSignal?

By default, Angular checks signal updates with Object.is, which treats every freshly parsed API object as a brand-new value. Therefore, pass a custom equal comparator whenever computation returns an object or array slice so downstream computed() views skip redundant recalculations when key fields match.

Anil Mehra on November 29, 2026 Angular Frontend Development Web Development
previous article
Next article

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

About the Author

Anil Mehra

Anil Mehra

Software Engineer · Google AI Certified

Anil Mehra is a Software Engineer specializing in Angular (NgRx, SignalStore, RxJS), React, TypeScript, Node.js, PHP, and MySQL. Holding the Google AI Professional Certificate, he bridges production web architecture with practical AI-powered workflows.

Google AI Professional Certificate official badge

Google AI Professional Certificate

Google · Coursera Credential ↗

About & Consulting · Instagram · LinkedIn

Recent Guides

  • claude sonnet 4.5 retirement migration guide banner
    Claude Sonnet 4.5 Retirement Hits Today: How I Migrated Node.js Calls to Sonnet 5.5November 30, 2026
  • speculation rules api instant prerender LCP guide banner
    Speculation Rules API Guide: Cut Route LCP to 38ms Without Phantom AnalyticsNovember 30, 2026
  • vite 8.4 release strict allow-list security wasm imports banner
    Vite 8.4 Release Brings Strict Allow-List Dev Security and Wasm Source ImportsNovember 29, 2026
  • Angular linkedSignal TypeScript guide banner showing writable dependent state and previous.value
    Angular linkedSignal in TypeScript: Fix effect() Write Loops & Preserve Previous StateNovember 29, 2026

Engineering Topics

  • Angular 13
  • Frontend Development 4
  • Node.js 3
  • PHP & MySQL 2
  • React & TypeScript 2
  • SEO & Performance 2
  • Tech & AI News 4
  • Web Development 19
  • Wordpress Plugins 1
CoreGamix — Full-Stack Engineering & Developer ToolsCoreGamix — Full-Stack Engineering & Developer Tools

contact

support@coregamix.com

© 2026 CoreGamix. All Rights Reserved.  |  About  |  Privacy Policy  |  Terms of Use  |  Contact

Back to top