惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
V
V2EX
博客园 - 【当耐特】
Vercel News
Vercel News
雷峰网
雷峰网
爱范儿
爱范儿
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Microsoft Azure Blog
Microsoft Azure Blog
F
Full Disclosure
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
NISL@THU
NISL@THU
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Attack and Defense Labs
Attack and Defense Labs
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
Microsoft Security Blog
Microsoft Security Blog
腾讯CDC
P
Proofpoint News Feed
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
K
Kaspersky official blog
I
InfoQ
Google Online Security Blog
Google Online Security Blog
L
LINUX DO - 最新话题
Project Zero
Project Zero
Engineering at Meta
Engineering at Meta
V
Visual Studio Blog
AI
AI
Schneier on Security
Schneier on Security
B
Blog RSS Feed
T
Tor Project blog
H
Help Net Security
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
T
Threat Research - Cisco Blogs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
C
Cyber Attacks, Cyber Crime and Cyber Security
G
Google Developers Blog
Google DeepMind News
Google DeepMind News
V2EX - 技术
V2EX - 技术
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
A
Arctic Wolf
Webroot Blog
Webroot Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Angular Signals and Effects
atilla baspinar · 2026-06-25 · via DEV Community

Version coverage

  • signal(), computed(), effect(), toSignal(), toObservable() — stable since Angular 17 (developer preview in Angular 16)
  • Effect onCleanup — stable since Angular 17
  • Zoneless mode — stable since Angular 18, default since Angular 21

A signal is a reactive value container. When a signal's value changes, Angular knows exactly which parts of the UI depend on it and updates only those parts — no full component scan needed.


1. Writable signals

Create a signal with signal(), passing the initial value. Read it by calling it like a function. Update it with set() or update().

import { signal } from '@angular/core';

export class CounterComponent {
  count = signal(0);

  increment() {
    this.count.update(c => c + 1); // derive next value from current
  }

  reset() {
    this.count.set(0); // set an explicit value
  }
}

set() replaces the value. update() receives the current value and returns the next one.


2. Computed signals

computed() creates a read-only signal whose value is derived from other signals. Angular evaluates the derivation lazily (only when first read) and caches the result. When any dependency signal changes, the cached value is invalidated and recalculated on the next read.

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

export class CartComponent {
  items = signal<{ price: number }[]>([]);
  total = computed(() => this.items().reduce((sum, item) => sum + item.price, 0));
}

total always reflects the current sum of items. You never call .set() on it — Angular manages it.


3. Reading signals in templates

In a template, you read a signal by calling it as a function. Angular automatically tracks every signal called during template rendering and re-renders the component whenever any of those signals change.

<!-- counter.html -->
<p>Count: {{ count() }}</p>
<p>Total: {{ total() }}</p>
<button (click)="increment()">+1</button>

There is no async pipe, no subscription, and no manual change detection call needed. Angular handles all of it.


4. Why you don't "subscribe" to signals in the component class

Reading a signal in the component class (outside a reactive context) just returns the current value at that instant — it does not set up a reactive dependency. The read is synchronous and stateless.

ngOnInit() {
  const current = this.count(); // reads the value once — no subscription
  console.log(current);         // this will NOT re-run when count changes
}

This is intentional. Signals are not Observables. There is no .subscribe() method. If you need to react to signal changes in the class — for example to trigger a side effect — use effect().


5. effect() — reacting to signal changes in the class

effect() creates a reactive side effect. Angular runs its callback immediately, tracks which signals are read inside it, and re-runs the callback automatically whenever any of those signals change.

Use effect() when you need to bridge a signal to a non-reactive API: logging, calling a third-party library, writing to localStorage, or manipulating the DOM directly.

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

export class ThemeComponent {
  theme = signal<'light' | 'dark'>('light');

  constructor() {
    effect(() => {
      document.body.setAttribute('data-theme', this.theme()); // runs whenever theme changes
    });
  }
}

effect() must be called in an injection context — the constructor or a field initializer. It cannot be called inside a lifecycle hook like ngOnInit.

Why not just use a getter or computed()? computed() is for deriving reactive state. effect() is for side effects — actions with no return value that touch something outside Angular's reactivity system.


6. Effect cleanup

When an effect re-runs (because a dependency changed) or when the component is destroyed, you may need to clean up work from the previous run — cancel a timer, abort a fetch, remove a listener. The effect callback receives an optional onCleanup function for this purpose.

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

export class PollingComponent {
  interval = signal(3000);

  constructor() {
    effect((onCleanup) => {
      const id = setInterval(() => {
        this.fetchData();
      }, this.interval()); // tracked — effect re-runs if interval changes

      onCleanup(() => {
        clearInterval(id); // called before the next run, or when the component is destroyed
      });
    });
  }

  private fetchData() { /* ... */ }
}

The sequence when interval changes:

  1. onCleanup callback runs → clearInterval(id) cancels the old timer
  2. Effect re-runs → a new setInterval starts with the updated value

Without onCleanup, changing interval would start a new timer on each change while the old ones kept running.

7. Signals vs. Zone.js change detection

Before signals, Angular relied on Zone.js to detect when anything in the app might have changed. Zone.js monkey-patches browser APIs (setTimeout, event listeners, Promises, etc.) so Angular knows when to trigger a full change detection scan of the component tree.

Signals make this unnecessary. Because Angular knows exactly which signal each template reads, it can skip the full scan and update only the components that actually depend on a changed value. This is the foundation of Angular's zoneless mode, which is stable from Angular 18+ and the default from Angular 21+. In zoneless mode, Zone.js is not loaded at all — change detection is driven entirely by signals.

In practice for new apps: prefer signals over @Input() / @Output() with plain class properties. Signals are what makes zoneless possible.


8. Signals and RxJS

Signals and RxJS solve overlapping but different problems. Angular provides an interop layer in @angular/core/rxjs-interop so you can use both together where needed.

When to use signals vs. RxJS

Use signals when… Use RxJS when…
Holding and deriving UI state Handling async streams (HTTP, WebSocket, events)
Driving template rendering Combining, debouncing, or transforming event sequences
Replacing @Input() / @Output() You need operators like switchMap, debounceTime, combineLatest
Working in a zoneless app Integrating with libraries that return Observables

The general pattern in modern Angular: use RxJS for data fetching and complex async logic, then convert the result to a signal for the template.

toSignal() — Observable → Signal

toSignal() subscribes to an Observable and exposes its latest value as a read-only signal. The subscription is automatically cleaned up when the component is destroyed.

import { toSignal } from '@angular/core/rxjs-interop';
import { HttpClient } from '@angular/common/http';

export class UsersComponent {
  private http = inject(HttpClient);

  users = toSignal(
    this.http.get<User[]>('/api/users'),
    { initialValue: [] }   // signal value before the Observable emits
  );
}

@for (user of users(); track user.id) {
  <li>{{ user.name }}</li>
}

initialValue sets the signal's value before the Observable has emitted. Without it, the signal type includes undefined until the first emission.

toObservable() — Signal → Observable

toObservable() wraps a signal as an Observable. It emits the signal's latest value after each change stabilises (not synchronously on every .set() call). Use it when you need to pipe a signal through RxJS operators.

import { toObservable } from '@angular/core/rxjs-interop';
import { debounceTime, switchMap } from 'rxjs/operators';

export class SearchComponent {
  query = signal('');

  results = toSignal(
    toObservable(this.query).pipe(
      debounceTime(300),
      switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`))
    ),
    { initialValue: [] }
  );
}

This pattern — toObservable → RxJS pipeline → toSignal — is the idiomatic way to do debounced search or any async transformation driven by a signal.


9. input(), model(), and output()

Angular 17+ introduced decorator-free alternatives to @Input(), @Output(), and two-way binding. Two of them are signals; one is not.

input() — read-only signal input (Angular 17.1+)

input() replaces @Input(). It returns an InputSignal — a read-only signal whose value is set by the parent. Because it is a signal, you can use it directly inside computed() and effect() without any extra wiring.

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

export class UserCardComponent {
  // optional with a default
  name = input('Anonymous');

  // required — throws at runtime if parent does not provide it
  userId = input.required<number>();

  // derived value reacts automatically when userId changes
  profileUrl = computed(() => `/users/${this.userId()}`);
}

<!-- user-card.html — read signals with () just like any other signal -->
<h2>{{ name() }}</h2>
<a [href]="profileUrl()">Profile</a>

Because name and profileUrl are signals, they must be called with () in the template. This is different from @Input() where you would write {{ name }} without parentheses. The () is what tells Angular to track the value reactively and re-render when it changes.

<!-- parent template -->
<app-user-card [userId]="42" [name]="'Alice'" />

InputSignal is read-only — calling .set() or .update() on it is a compile error.


model() — writable signal for two-way binding (Angular 17.2+)

model() creates a ModelSignal, which is a writable signal that also acts as an input/output pair. The parent can bind to it with [()] syntax; the child can update it with .set() or .update() and the new value is automatically propagated back to the parent.

Under the hood, model() declares both an input named property and an output named propertyChange — the same convention used by @Input() + @Output() two-way binding, but without the boilerplate.

import { model } from '@angular/core';

export class RatingComponent {
  // writable signal — parent can read it, child can change it
  rating = model(0);

  increase() {
    this.rating.update(r => r + 1); // parent's bound variable updates automatically
  }
}

<!-- rating.html — read with () like any writable signal -->
<p>Current rating: {{ rating() }}</p>
<button (click)="increase()">+</button>

rating() reads the current value reactively. When increase() calls this.rating.update(), Angular updates both the child template and the parent's bound variable in one step. Compare this to @Input() where you would write {{ rating }} without () and the parent's variable would not update at all without a manual @Output() emit.

<!-- parent template -->
<app-rating [(rating)]="userRating" />
<p>Parent sees: {{ userRating }}</p>

[(rating)] desugars to [rating]="userRating" (ratingChange)="userRating = $event" — exactly what you would write manually with @Input() + @Output(). The difference is that model() sets this up in one line, and this.rating is a real signal usable inside computed() and effect().

@Input() + @Output() model()
Two-way binding syntax [(prop)] [(prop)]
Value as signal No Yes — ModelSignal
Writable from child Manual emit .set() / .update()
Use in computed() No Yes

output() — decorator-free event emitter (Angular 17.3+)

output() replaces @Output() + EventEmitter. It is not a signal. It returns an OutputEmitterRef<T> which only has one method: .emit(). You cannot call this.myOutput() to read a value from it — it is a one-way notification channel, not a reactive value.

import { output } from '@angular/core';

export class SearchComponent {
  searched = output<string>(); // OutputEmitterRef<string> — not a signal

  onSearch(query: string) {
    this.searched.emit(query);
  }
}

<!-- parent template — identical to @Output() usage -->
<app-search (searched)="handleSearch($event)" />

output() belongs to the same decorator-free API family as input() and model(), but it has no connection to signal reactivity. It is included here for completeness.

input() model() output()
Type returned InputSignal ModelSignal OutputEmitterRef
Is a signal Yes (read-only) Yes (writable) No
Direction Parent → Child Parent ↔ Child Child → Parent
Usable in computed() / effect() Yes Yes No
Replaces @Input() @Input() + @Output() pair @Output() + EventEmitter

10. Signals and effects compared to React

If you come from React, Angular signals and effects map closely to concepts you already know — but with two key structural differences: Angular tracks dependencies automatically (no dependency arrays), and a signal change only updates the parts of the template that read it, not the whole component.

useState vs signal()

Both hold reactive state. The API is slightly different:

// React
const [count, setCount] = useState(0);
setCount(5);                        // set a value
setCount(prev => prev + 1);         // derive from previous

// Angular
count = signal(0);
this.count.set(5);                  // set a value
this.count.update(prev => prev + 1); // derive from previous

Reading is the biggest visible difference. In React, count is a plain variable captured by the render closure. In Angular, count() is a function call — the () is what registers the reactive dependency.

React useState Angular signal()
Read count count()
Write (replace) setCount(val) count.set(val)
Write (derive) setCount(prev => ...) count.update(prev => ...)
On change Whole component re-renders Only signal-dependent DOM updates
Stale closure risk Yes — closures capture old values No — count() always reads current value

useMemo vs computed()

Both derive a cached value from other state. The critical difference is that React requires you to list dependencies manually, while Angular tracks them automatically by observing which signals are called during the derivation.

// React — dependency array is manual and error-prone
const total = useMemo(
  () => items.reduce((sum, item) => sum + item.price, 0),
  [items]   // must be kept in sync by hand
);

// Angular — no dependency array; Angular tracks items() automatically
total = computed(() => this.items().reduce((sum, item) => sum + item.price, 0));

If you add a new signal inside the computed() body, Angular picks it up automatically. In React, forgetting to add a dependency to useMemo silently produces stale values.

useEffect vs effect()

Both run a side effect in response to state changes. Same automatic vs. manual dependency distinction applies.

// React — manual dependency array
useEffect(() => {
  document.body.setAttribute('data-theme', theme);
}, [theme]);   // must list every dependency

// Angular — automatic tracking
effect(() => {
  document.body.setAttribute('data-theme', this.theme()); // theme() is tracked automatically
});

Cleanup — return vs onCleanup

React's cleanup is a return value from the effect callback. Angular's is a parameter passed into it.

// React — return a cleanup function
useEffect(() => {
  const id = setInterval(() => fetch('/api/poll'), 3000);
  return () => clearInterval(id);   // runs before next effect or on unmount
}, []);

// Angular — onCleanup parameter
effect((onCleanup) => {
  const id = setInterval(() => this.poll(), this.interval());
  onCleanup(() => clearInterval(id)); // runs before next effect or on destroy
});

Both cleanup functions run at the same moments: before the effect re-runs due to a dependency change, and when the component is destroyed/unmounted.

Summary of differences

React Angular
Dependency tracking Manual arrays ([dep1, dep2]) Automatic — reads inside the callback
On state change Whole component re-renders Only the affected template nodes update
Stale closure problem Yes — must manage carefully No — signals always read current value
Derived state useMemo with dep array computed() — no array needed
Side effects useEffect with dep array effect() — no array needed
Cleanup Return a function onCleanup parameter
Where effects can be called Top level of component only Constructor or field initializer

11. Summary

Signal Computed Effect RxJS Observable
Purpose Holds reactive state Derives reactive state Side effects on signal change Async event/data streams
Writable Yes (set, update) No N/A No (push-based)
Reactive in template Yes — call as value() Yes — call as value() N/A Only via async pipe or toSignal()
Reactive in class Only inside effect() or computed() Only inside effect() or computed() Yes — auto-tracks reads Yes — via .subscribe()
Cleanup N/A N/A onCleanup callback unsubscribe() or takeUntilDestroyed
Zoneless compatible Yes Yes Yes Yes, via toSignal()