Search code examples
javascriptangulartypescriptrxjssignals

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?


Solution

  • 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;
    });