# OnChanges interface

In 
Published 2024-01-06

This tutorial explains how we can implement OnChanges in Angular.

In Angular, the OnChanges lifecycle hook is used when you want to perform actions in response to changes in input properties of a component. The OnChanges interface provides a method named ngOnChanges(), which is c**alled whenever the input properties of a component change**.

Here's a step-by-step explanation of how to implement OnChanges in an Angular component:

# Import OnChanges

Import the OnChanges interface from @angular/core.

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

# Implement OnChanges in the Component Class

Implement the OnChanges interface in your component class. This involves adding implements OnChanges to the class declaration and providing the necessary ngOnChanges() method.

@Component({
  selector: 'app-my-component',
  template: '<p></p>',
})
export class MyComponent implements OnChanges {
  @Input() inputProperty: string;

  ngOnChanges(changes: SimpleChanges): void {
    // Handle changes to input properties here
    if (changes.inputProperty) {
      const newInputPropertyValue = changes.inputProperty.currentValue;
      const previousInputPropertyValue = changes.inputProperty.previousValue;
      console.log(`Input property changed from ${previousInputPropertyValue} to ${newInputPropertyValue}`);
    }
  }
}

In this example, the MyComponent class implements the OnChanges interface and provides the ngOnChanges() method and the inputProperty is marked as an input property, and changes to it will trigger the ngOnChanges method.

# Accessing Changes in ngOnChanges

Inside the ngOnChanges() method, you can access the changes to input properties through the changes parameter of type SimpleChanges.

ngOnChanges(changes: SimpleChanges): void {
  if (changes.inputProperty) {
    const newInputPropertyValue = changes.inputProperty.currentValue;
    const previousInputPropertyValue = changes.inputProperty.previousValue;
    console.log(`Input property changed from ${previousInputPropertyValue} to ${newInputPropertyValue}`);
  }
}

The changes object contains information about all input properties that have changed. In this example, it checks if inputProperty has changed and logs the current and previous values.

The OnChanges lifecycle hook is useful when you need to react to changes in input properties and perform actions accordingly. It is important to note that the ngOnChanges method is called whenever any input property changes, so you can use this hook to handle multiple input properties within your component.