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

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