Angular Computed Signals
Angular Signals can be combined to create computed values that automatically update when any of the dependent signals change.
Define one using computed
and specifying a derivation function:
celsius = signal(0);
fahrenheit = computed(() => this.celsius.value * 9 / 5 + 32);
This example demonstrates a temperature converter. The celsius
Signal holds the temperature in Celsius, and fahrenheit
is a computed Signal that automatically updates its value based on the current value of celsius
.
Below Angular component (Standalone) used for demonstration
import 'zone.js';
import { Component } from '@angular/core';
import { signal, computed } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
imports: [FormsModule],
selector: 'app-computed-signals',
standalone: true,
template: `
<hr>
<h1> Computed signals </h1>
<div>Celsius: {{ celsius() }}°C</div>
<div>Fahrenheit: {{ fahrenheit() }}°F</div>
<input [value]="celsius" type="number" placeholder="Enter Celsius"
(input)="celsius.set($any($event.target).value)"
>
`,
})
Computed signals are not writable signals, which means You cannot directly assign values to a computed signal (fahrenheit
). That is,
this.fahrenheit.set(0);
Source code is at stack-blitz.com
Weekend coding: Where the keyboard is your compass, imagination your map, and deadlines don't exist. Passion and creativity lead the way, turning curiosity into reality. #WeekendCoding #DeveloperLif
Subscribe to my newsletter
Read articles from VJ directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
VJ
VJ
#Coding #Tech #FullStack #WebDev