In this article, we are going to look at how ngOnChanges Life cycle hook works in Angular. The Angular fires ngOnChanges or OnChanges, when the Angular detects changes to the @Input properties of the Component. It gets the changes in the form of simplechanges object. We will be learning all these in this tutorial.
Table of Contents
What is nOnChanges Life cycle hook
The ngOnChnages is a life cycle hook, which angular fires when it detects changes to data-bound input property. This method receives a SimpeChanges
object, which contains the current and previous property values.
There are several ways the parent component can communicate with the child component. One of the ways is to use the @Input decorator. We looked at this in our tutorial passing data to Child Components
Let us just recap what we have done in that tutorial
The child Component decorates the property using the @Input decorator.
1 2 3 | @Input() message: string; |
And then parent passes the data to the child component using property binding as shown below
1 2 3 | <child-component [message]=message></child-component>` |
Whenever the parent changes the value of the message property, the Angular raises the OnChanges
hook event in the child component, so that it can act upon it.
How does it work
The ngOnChanges()
method takes an object that maps each changed property name to a SimpleChange
object, which holds the current and previous property values. You can iterate over the changed properties and act upon it.
SimpleChange
SimpleChange
is a simple class, which has three properties
Property Name | Description |
---|---|
previousValue:any | Previous value of the input property. |
currentValue:any | New or current value of the input property. |
FirstChange():boolean | Boolean value, which tells us whether it was the first time the change has taken place |
SimpleChanges
Every @Input property of our component gets a SimpleChange
object (if Property is changed)
SimpleChanges
is the object that contains the instance of all those SimpleChange
objects. You can access those SimpleChange
objects using the name of the @Input property as the key
For Example, if the two Input properties message1
& message2
are changed, then the SimpleChanges
object looks like
1 2 3 4 5 6 7 8 9 10 11 12 | { "message1": { "previousValue":"oldvalue", "currentValue":"newvalue", "firstChange":false } }, "message2": { "previousValue":"oldvalue", "currentValue":"newvalue", "firstChange":false } } } |
And if the input property is an object (customer object with name & code property) then the SimpleChanges
would be
1 2 3 4 5 6 7 8 | { "Customer": {"previousValue":{"name":"Angular","code":"1"}, "currentValue":{"name":"Angular2","code":"1"}, "firstChange":false} } |
ngOnChanges example
Create a class customer.ts
under src/app folder.
1 2 3 4 5 6 | export class Customer { code: number; name: string; } |
Parent Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import { Component} from '@angular/core'; import { Customer } from './customer'; @Component({ selector: 'app-root', template: ` <h1>{{title}}!</h1> <p> Message : <input type='text' [(ngModel)]='message'> </p> <p> Code : <input type='text' [(ngModel)]='code'></p> <p> Name : <input type='text' [(ngModel)]='name'></p> <p><button (click)="updateCustomer()">Update </button> <child-component [message]=message [customer]=customer></child-component> ` , styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ngOnChanges'; message = ''; customer: Customer = new Customer(); name= ''; code= 0; updateCustomer() { this.customer.name = this.name; this.customer.code = this.code; } } |
Lets us look at the code
We have 3 user input fields for the message
, code
and name
. The UpdateCustomer
button updates the Customer object.
1 2 3 4 5 6 | <p> Message : <input type='text' [(ngModel)]='message'> </p> <p> Code : <input type='text' [(ngModel)]='code'></p> <p> Name : <input type='text' [(ngModel)]='name'></p> <p><button (click)="updateCustomer()">Update </button> |
The message
and Customer
is bound to the child component using the property binding
1 2 3 | <child-component [message]=message [customer]=customer></child-component> |
The AppComponent
class has a message
& customer
property. We update customer
object with new code
& name
when user clicks the updateCustomer
button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | export class AppComponent { title = 'ngOnChanges'; message = ''; customer: Customer = new Customer(); name= ''; code= 0; updateCustomer() { this.customer.name = this.name; this.customer.code = this.code; } } |
Child Component
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import { Component, Input, OnInit, OnChanges, SimpleChanges, SimpleChange,ChangeDetectionStrategy } from '@angular/core'; import { Customer } from './customer'; @Component({ selector: 'child-component', template: `<h2>Child Component</h2> <p>Message {{ message }} </p> <p>Customer Name {{ customer.name }} </p> <ul><li *ngFor="let log of changelog;"> {{ log }}</li></ul> ` }) export class ChildComponent implements OnChanges, OnInit { @Input() message: string; @Input() customer: Customer; changelog: string[] = []; ngOnInit() { console.log('OnInit'); } ngOnChanges(changes: SimpleChanges) { console.log('OnChanges'); console.log(JSON.stringify(changes)); // tslint:disable-next-line:forin for (const propName in changes) { const change = changes[propName]; const to = JSON.stringify(change.currentValue); const from = JSON.stringify(change.previousValue); const changeLog = `${propName}: changed from ${from} to ${to} `; this.changelog.push(changeLog); } } } |
Let us look at each line of code in detail
First, We import the Input
, OnInit
, OnChanges
, SimpleChanges
, SimpleChange
from Angular Core
1 2 3 | import { Component, Input, OnInit, OnChanges, SimpleChanges, SimpleChange } from '@angular/core'; |
The Template displays the message
& name
property from the customer
object. Both these properties are updated from the parent component.
1 2 3 4 5 6 | template: `<h2>Child Component</h2> <p>Message {{ message }} </p> <p>Customer Name {{ customer.name }} </p> |
We also display the changelog using ngFor Directive.
1 2 3 | <ul><li *ngFor="let log of changelog;"> {{ log }}</li></ul> ` |
The child Component implements the OnChanges
& OnInit life cycle hooks.
1 2 3 4 5 | export class ChildComponent implements OnChanges, OnInit { |
We also define message
& customer
property, which we decorate with the @Input decorator. The parent component updates these properties via Property Binding.
1 2 3 4 5 | @Input() message: string; @Input() customer: Customer; changelog: string[] = []; |
The OnInit hook
1 2 3 4 5 | ngOnInit() { console.log('OnInit'); } |
The ngOnChnages
hook gets all the changes as an instance of SimpleChanges
. This object contains the instance of SimpleChange
for each property
1 2 3 4 5 | ngOnChanges(changes: SimpleChanges) { console.log('OnChanges'); console.log(JSON.stringify(changes)); |
We, then loop through each property of the SimpleChanges
object and get a reference to the SimpleChange
object.
1 2 3 4 | for (const propName in changes) { const change = changes[propName]; |
Next, we will take the current & previous value of each property and add it to change log
1 2 3 4 5 6 7 8 9 | const to = JSON.stringify(change.currentValue); const from = JSON.stringify(change.previousValue); const changeLog = `${propName}: changed from ${from} to ${to} `; this.changelog.push(changeLog); } } } |
That’s it.
Now our OnChanges
hook is ready to use.
Now, run the code and type the Hello
and you will see the following log
1 2 3 4 5 6 7 8 9 | message: changed from undefined to "" customer: changed from undefined to {} message: changed from "" to "H" message: changed from "H" to "He" message: changed from "He" to "Hel" message: changed from "Hel" to "Hell" message: changed from "Hell" to "Hello" |
Open the developer console and you should see the changes object
Note that the first OnChanges
fired before the OnInit hook. This ensures that initial values bound to inputs are available when ngOnInit()
is called
OnChanges does not fire always
Now, change the customer code
and name
and click UpdateCustomer
button.
The Child Components displays customer Name
, but OnChanges
event does not fire.
This behavior is by design.
Template is Updated
Updating the DOM is part of Angular’s change detection mechanism The change detector checks each and every bound property for changes and updates the DOM if it finds any changes.
In the child component template, we have two bound properties. {{ message }}
& {{ customer.name }}
. Hence the change detector checks only these two properties and updates the DOM. The customer object also has code
property. The change detector will never check it.
Why onChanges does not fire?
The Change detector also raises the OnChanges
hook. But it uses a different techniques for comparison.
The change detector uses the === strict equality operator for detecting changes to the input properties. For primitive data types like string, the above comparison works perfectly
But in the case of an object like a customer, this fails. For Arrays/objects, the strict checking means that only the references are checked. Since the reference to the customer stays the same the Angular does not raise the OnChanges hook.
That leaves us two possible solutions
- Create a new customer and copy the old data to new customer
- We can Perform our own change detection using the ngDoCheck lifecycle hook
Update the updateCustomer method and create a new instance of customer every time
1 2 3 4 5 6 7 | updateCustomer() { this.customer= new Customer(); //Add this this.customer.name = this.name; this.customer.code = this.code; } |
Now, run the code, you will see onChanges
event fired when customer is updated
The second method is to use the ngDoCheck lifecycle hook, which we will cover in the next tutorial
Source Code
Summary
In this tutorial, we learned how to use ngOnChanges method. We also, learned how to find out which properties are changed using SimpleChanges object
33333
I really like this tutorial. Thanks!
In reference section on spelling mistake is there –
SimpleCharges
In refernce correct spelling mistake –
SimpleCharges API
Thank you very much, very very good tuto
I think the constructor of Customer shoudd be implemented like that :
new Customer(this.code = null , this.name=”);
Or make the properties optionnals in the model :
export class Customer {
constructor (public code?: number, public name?: string) {
}
}
Thanks