angulartypescriptonchangeangular-lifecycle-hooksngonchanges

is it possible to have currentValue = previousValue in ngOnChanges


As per my understanding, the ngOnChanges hook is only invoked when an input property undergoes a change. Therefore, it seems logical to say that within the ngOnChanges hook, changes.property?.currentValue and changes.property?.previousValue are always different. In other words, will this code make sense:

 ngOnChanges(changes: SimpleChanges): void {
   if (changes.steps?.currentValue !== changes.steps?.previousValue) {
        // do something only if value is really changed
    }
 }

I am seeking clarification to ensure that there isn't a specific scenario or edge case where these values might unexpectedly be the same.


Solution

  • ngOnChanges is triggered when any input property changes, so for any single property that's being monitored, the currentValue will always be different than previousValue because those values would be mapped only if the change actually exists. Thus, the posted condition will always return true. Keep in mind, though, that there might be a SimpleChanges object returned by the hook, but changes might not be of the property you're checking for, i.e. changes.steps, so yeah be sure to have the ? there as you do now.