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

  1. Computed signals are derived from other signals.
  2. Defined using the computed() function with a callback.


Issue with Normal Properties

  1. area depends on height and width.
  2. When height or width changes, area does not update automatically.


Using Computed Signals

  1. Convert height and width into signals.
  2. Create area as a computed signal.
  3. area updates automatically when height or width changes.
  4. 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

  1. computed() always uses a callback function.
  2. Computed signals cannot use set() or update().
  3. Only the required DOM updates, not the whole component.
  4. effect() runs only when a signal is accessed inside it.