Leogout
Leogout

Reputation: 1247

How do Angular's computed() signals work internally?

I don't understand how computed() works internally. How does Angular knows when to update it ? The docs don't mention it.

From the docs :

The doubleCount signal depends on the count signal. Whenever count updates, Angular knows that doubleCount needs to update as well. doubleCount's derivation function does not run to calculate its value until the first time you read doubleCount. The calculated value is then cached, and if you read doubleCount again, it will return the cached value without recalculating. If you then change count, Angular knows that doubleCount's cached value is no longer valid, and the next time you read doubleCount its new value will be calculated.

They say that "Angular knows" two times but never explain how Angular knows this.

import { Component, computed, input } from '@angular/core';
import { ComponentChartData } from '../../../../models/component';

@Component({
  selector: 'app-chart',
  standalone: true,
  templateUrl: './chart.component.html',
  styleUrl: './chart.component.scss',
})
export class ChartComponent {
  chartData = input.required<ComponentChartData>();
  datasets = computed(() => this.chartData().datasets);
}

Upvotes: 1

Views: 438

Answers (1)

Dariusz
Dariusz

Reputation: 314

This question might be answered on different levels of complexity. Without digging into source code the 'simple' answer is that Angular uses Dynamic Dependency tracking if you want to dig into the source code I'd recommend to start with producerUpdateValueVersion. From other sources you might take a look at this blog post

Upvotes: 0

Related Questions