ngOnChanges() Exposed — Angular
Hello awesome people, in this article we are going to discuss ngOnchanges()
life cycle hook.
Okay first let’s discuss in short when
ngOnChanges()
is called.
Whenever bound input property changes, the life cycle hook ngOnChanges()
is called after that and it triggers before ngOnInit()
.
ngOnChanges()
the only hook which receives an argument. The argument is named as changes
and it is of typeSimpleChanges
.
It returns us the current value and previous value. Also, it gives us firstChange = true
as the value was previously undefined and now only it is initialized.
Okay cool, now let’s discuss when ngOnChanges()
is not triggered even though the view with respect to the changed value is updated in the child component where we listen to it using @Input()
decorator.
Let’s understand this by taking an example. We have one app component(parent) and one child component(child).
In the parent component, we have defined an array that holds string values and it is initially initialized with one value. Also, we have one function which updates the value at the zeroth index in the array.
From the parent component, we are passing that array to the child component. And we have one button which is bound to changeName()
function.
Note: [name]=”name” represents binding with a custom property
Now here array name is prefixed with the input decorator which receives its value from its parent component. So whenever we change/update the value of the array in the parent it is reflected in the child component.
And according to what we learned till now we know in this case the ngOnChanges()
the hook should fire coz as soon as the button is clicked the value in the array is updated.
But surprisingly the ngOnChanges()
hook didn’t fire and the view of the dom changed, i.e now the zeroth index of the array will be updated from name
to name changed.
and the same is reflected in the dom.
Let’s understand why
ngOnChanges()
didn’t triggered.
It is because both the array properties present in the parent as well as in the child, share the same memory location i.e they have the same reference point, and due to which the value of that array updated when we clicked the button but the reference remained same and this is the reason why ngOnChanges()
hook didn’t trigger.
Note: For Array and Object both this behaviour remains the same.
Now how we can trigger ngOnChanges()
the hook in this case? Well just change the reference of the array by creating a newly updated array and assigning it.
Something like the below example.
Conclusion
Now we know more about ngOnChanges()
then before. Hope you extracted some knowledge from it. In case of any doubt or if you just want to say Hi! feel free to reach me on LinkedIn or GitHub.
If you like the blog make sure to take a look at my YouTube channel for more amazing stuff.