Tech Insights
Sithum Meegahapola
April 6, 2020

The purpose & usage of “SimpleChanges” in the ngOnChange function

The purpose & usage of “SimpleChanges” in the ngOnChange function

This article willdescribe what the SimpleChanges object is, its purpose and how to use it.

What is SimpleChanges in Angular?

SimpleChanges is an Angular/Core feature that can be used to view the changesand a few more details of the declared property names in a component. It alsoneeds to be used in the Angular ngOnChange method to view the values changed andto carry out other relevant functions.

The ngOnChange is fired when the values are changed in a declared property. Inthat method, parameter can be set to store the data, as below;  

In this way thesedetails can be checked using SimpleChanges:

                           

PreviesValue:

Gives the previous valueof the property.

currentValue:

Gives the current valueof the property.

firstChange():

this is a method and itwill return true if the previous value and the current values are the same;else it will return false.

What can weuse this for?

Let's assume we havethese properties declared in the Angular Component.

What if, a method has tobe called or some other task needs to be executed, when the value of one ofthese properties is changed? If this is done manually, an extra variable isneeded to hold the current value to compare with the new value to perform thistask.

This is where“SimpleChanges” is going to help you.

With SimpleChanges youcan perform the tasks mentioned above in the ngOnChange function in a simplemanner.

Let's see how it can bedone.

How to use“SimpleChanges”?

First, add thengOnChange function to your component and use the SimpleChanges as a parameteras below.

Let's assume theprevious value and the current value of the “selectedModuleKey” property needsto be checked and if it has changed, a method has to be executed.

This is how to get it done.

Let me explain what Ihave done in the above code.

The ngOnChange functionis used to call the method, if there are any value changes to the properties.Therefore, SimpleChange value of the “selectedModuleKey” has to be obtained andit is done as below.

And then, the“firstChange()” method is called in the “if” condition that is in theSimpleChange class, to check if the previous value is the same as the currentvalue of this property (selectedModuleKey). This method will return true if thevalues are same. Since we need to fire the method only if the values aredifferent, I have reversed the boolean result to run it if the method returnsfalse.

Always remember that anyof your property can be accessed similar to the way “selectedModuleKey” wasaccessed, as below.

let change =changes[‘the property name];

This is how“SimpleChanges” object in ngOnChange can be used to execute a task of thiskind. Hope this helps in your day-to-day Angular development.