Computed Signals - Performance Optimization
Computed Signals (Angular)
Computed Signals are signals that depend on other signals.
They cannot be updated directly and update automatically when their dependent signals change.
They are used mainly for performance optimization.
What are Computed Signals
- Computed signals are derived from other signals.
- Defined using the
computed()function with a callback.
Issue with Normal Properties
areadepends onheightandwidth.- When
heightorwidthchanges,areadoes not update automatically.
Using Computed Signals
- Convert
heightandwidthinto signals. - Create
areaas a computed signal. areaupdates automatically whenheightorwidthchanges.- No manual recalculation needed.
Code Example
HTML
<h1>Computed Signals</h1>
<h1>Area : {{ area() }}</h1>
<button (click)="handleHeight()">Update Height</button>
TypeScript
export class App {
height = signal(100);
width = signal(20);
area = computed(() => this.height() * this.width());
constructor() {
effect(() => {
console.log("is updating?");
// console.log("area is :", this.area());
});
}
handleHeight() {
this.height.set(this.height() + 10);
}
}
Important Points
computed()always uses a callback function.- Computed signals cannot use
set()orupdate(). - Only the required DOM updates, not the whole component.
effect()runs only when a signal is accessed inside it.