How can we get previous and current value of a Signal based Input in Angular v17?

373 views Asked by At

In earlier versions of Angular, ngOnChanges provides SimpleChange which is helpful in getting previousValue and currentValue of an @Input property.

I want this same functionality in Signal based Inputs but I couldn't find any way to get previous value of Input. Is there any way around this?

I read about using @angular/core/rxjs-interop to convert the signal to Observable and use pairwise but pairwise emits on the second and subsequent emissions from the source Observable, but not on the first emission.

2

There are 2 answers

5
Lakhveer On BEST ANSWER

It was rather simple. Apparently, Angular signal input still supports the SimpleChanges interface. So we can use the same old way of ngOnChanges(changes: SimpleChanges) to get the previous value.

But, I've heard that Angular team is thinking of deprecating ngOnChanges in future. So not sure how future compatible this code is gonna be. Any suggestions are welcome.

Here is an example: https://stackblitz.com/edit/stackblitz-starters-dkoxpz?file=src%2Fmain.ts

1
Matthieu Riegler On

Some libraries like ng-extension provide helper functions to this kind of purposes.

For example computedPrevious or computedExtended allow access to a previous value.

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