Blog>
Snippets

Using NgOnChanges for Detecting Input Changes

Provides an example of implementing the OnChanges lifecycle hook to react to changes in input properties, a part of Angular's unidirectional data flow pattern.
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-example-component',
  template: '<p>Previous value: {{ previousValue }} - Current value: {{ currentValue }}</p>'
})
export class ExampleComponent implements OnChanges {
  @Input() inputValue: string;
  previousValue: string;
  currentValue: string;

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.inputValue) {
      const change = changes.inputValue;
      this.previousValue = change.previousValue;
      this.currentValue = change.currentValue;
      // Additional logic here to respond to the change
    }
  }
}
This code defines an Angular component with an input property named 'inputValue'. It implements the OnChanges interface to detect and respond to changes in its input properties. Within the ngOnChanges method, it checks if 'inputValue' has changed, and if so, it updates the 'previousValue' and 'currentValue' properties with the respective values from the changes object. The template displays these values for demonstration.