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.
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.
@Input() message: string;
And then parent passes the data to the child component using property binding as shown below
<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.
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 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 |
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
{
"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
{
"Customer":
{"previousValue":{"name":"Angular","code":"1"},
"currentValue":{"name":"Angular2","code":"1"},
"firstChange":false}
}
Create a class customer.ts under src/app folder.
export class Customer {
code: number;
name: string;
}
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.
<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 theproperty binding
<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.
export class AppComponent {
title = 'ngOnChanges';
message = '';
customer: Customer = new Customer();
name= '';
code= 0;
updateCustomer() {
this.customer.name = this.name;
this.customer.code = this.code;
}
}
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
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.
template: `<h2>Child Component</h2>
<p>Message {{ message }} </p>
<p>Customer Name {{ customer.name }} </p>
We also display the changelog using ngFor Directive.
<ul><li *ngFor="let log of changelog;"> {{ log }}</li></ul> `
The child Component implements the OnChanges & OnInit life cycle hooks.
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.
@Input() message: string;
@Input() customer: Customer;
changelog: string[] = [];
The OnInit hook
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
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.
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
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
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
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.
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.
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
Update the updateCustomer method and create a new instance of customer every time
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
In this tutorial, we learned how to use ngOnChanges method. We also, learned how to find out which properties are changed using SimpleChanges object