Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use the previous value of a computed Angular signal?

I want to add each new value from signal A to the list value of signal B, similar to what you can do with the scan operator in RxJS. Ideally I'd want something like this: signalB = computed((value) => [...value, signalA()]). Can I somehow do that?

like image 444
Homo Civicus Avatar asked Nov 28 '25 18:11

Homo Civicus


1 Answers

v19+ Answer.

The framework provide the linkedSignal primitive for that.

import { linkedSignal } from '@angular/core';

const result = linkedSignal({
  source: count,
  computation: (count, previousValue) => {
    if (multiplier() % 2 === 0) {
      return count * multiplier();
    }
    return previousValue;
  },
});

Pre v19 answer

The framework doesn't propose something out-of-the-box, but the ngextension library has a neat extendedComputed

import { extendedComputed } from 'ngxtension/computed';

const multiplier = signal(2);
const count = signal(1);

const result = extendedComputed<number>((previousValue) => {
  // only compute when multiplier is even
  if (multiplier() % 2 === 0) {
    return count() * multiplier();
  }
  return previousValue;
});
like image 98
Matthieu Riegler Avatar answered Dec 01 '25 07:12

Matthieu Riegler