Demo
HTML
TS
CSS
⚡ Signal Example 8: Signal with Side Effect
🔔 Discover how Angular Signals can trigger side effects! This example shows how to use effect() to react to signal changes for logging, API calls, and more.
⚡ Signal with Side Effect
Count: 1000
🔔 Deep Dive: Side Effects with Angular Signals
Side effects are actions that happen in response to state changes—like logging, showing notifications, or making API calls. With Angular signals, you can use effect() to run code automatically whenever a signal changes.
The effect() function lets you react to signal changes. It runs your code every time the signal’s value updates, making it easy to handle side effects in a clean, declarative way.How This Example Works
- Signal Declaration: The count value is stored in a signal, e.g.
count = signal(0); - Effect Setup: The
effect(() => ...)function is used to run code whenevercount()changes. For example, you might log the new value or trigger an API call. - Triggering Changes: Clicking the Update Count button updates the signal, which in turn triggers the effect.
- Reactive UI: The template uses
1000to display the value. Whenever the signal changes, Angular updates the UI and runs the effect. - Cleanup: Effects can be cleaned up automatically when the component is destroyed, preventing memory leaks.
Why Use Effects with Signals?
- Declarative Side Effects: Keep your side-effect logic close to your state logic.
- Automatic Tracking: Effects run only when their dependent signals change.
- Readability: The code is easy to follow and maintain.
- Separation of Concerns: UI updates and side effects are handled separately but reactively.
★Effects make it easy to react to signal changes, keeping your Angular apps interactive and responsive!
