Angular Signals: Computed Values

Angular Signals: Computed Values

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.


Updates

Subscribe to my personal newsletter.

Join others! 100% Free. No spam. Privacy Policy

Related posts