Angular Signals: Computed Values
Simplify your code in your Angular apps by using Signals
Signals is a powerful new feature in the Angular framework that allows developers to track how and where their state is used throughout an application, which can lead to significant optimization in rendering updates.
Generally they are just wrappers around a value that can notify interested consumers when that value changes. These signals can contain any value, from simple primitives to complex data structures.
One important thing to note is that a signal’s value is always read through a getter function, which allows Angular to track where the signal is used. Additionally, signals can be either writable or read-only, depending on the developer’s needs.
Table of Contents
Example
Here’s a simple example to help illustrate the concept further:
Suppose we’re building a weather app that displays Celsius and Fahrenheit temperatures. We can define two signals, celsius, and fahrenheit, and use them to compute each other’s values. Here’s what the code could look like:
import { Component } from "@angular/core";import { signal, computed } from "@angular/signals";
@Component({ selector: "weather-app", template: ` <p>Celsius: {{ celsius() }}</p> <p>Fahrenheit: {{ fahrenheit() }}</p> <button (click)="setCelsius(25)">Set Celsius to 25</button> `,})export class WeatherAppComponent { celsius = signal(0); fahrenheit = computed(() => this.celsius() * 1.8 + 32);
constructor() { effect(() => console.log("Celsius changed:", this.celsius())); }
setCelsius(newCelsius: number) { this.celsius.set(newCelsius); }}In this example, we define a signal celsius with an initial value of 0, and a computed value fahrenheit that depends on celsius. Whenever we change the value of celsius, the browser will log a message to the console. We also provide a button that sets the value of celsius to 25 when clicked.
Why?
Angular Signals help in building more performant and efficient applications. It reduces the amount of code required to manually update views whenever the data changes. With a clearer mental model of data flow, it is easier to maintain and debug applications.
- tags:
- typescript (5)
- angular (2)
- frontend development (2)
- web development (2)
- reactive programming (1)
- signals (1)
Related posts
- Server Actions in Next.js: Enhancing User Experience with Optimistic Updates May 6, 2023 Learn how to use Server Actions and experimental useOptimistic hook in Next.js
- Learn TypeScript with these resources April 2, 2016 New to TypeScript?
- 10x faster with TypeScript's Project Corsa March 11, 2025 Discover how Microsoft's bold move to port the TypeScript compiler to Go promises up to 10× speed improvements