ngOnChanges lifecycle hook

ngOnChanges is an Angular lifecycle hook that is called whenever one or more of the bound input properties of a component changes. This hook helps update the component’s state or view in response to changes to the input properties.

To use it, implement the OnChanges interface as follows:

The above ngOnChanges method will run every time the parent component updates the value of name. We can get more information about what changed using the parameter of that method, an object that maps each changed property name to an SimpleChange object. The SimpleChange object contains the following properties:

  • previousValue: The value of the property before it changed.
  • currentValue: The value of the property after it changed.
  • firstChange: boolean value, true if it’s the first change made to that input, false otherwise.

As an example, the above code would output that object to the console as follows:

You can find that example in action on Stackblitz. The most common real-life example of using ngOnChanges is to be notified when an object ID changes so the component can request data for that ID using a service that makes an HTTP request, for instance.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.