ANGULAR
Complete Angular Tutorial For Beginners Introduction to Angular | What is Angular? Architecture Overview & Concepts of Angular How to Install Angular How to Create a new project in Angular Bootstrapping in Angular: How It Works Internally Angular Components Overview & Examples Data Binding in Angular Interpolation in Angular Property Binding in Angular Event Binding in Angular ngModel & Two way Data binding in Angular NgModelChange & Change Event in Angular Child/Nested Components in Angular angular directives angular ngFor directive ngSwitch, ngSwitchcase, ngSwitchDefa ult Angular Example How to use ngIf, else, then in Angular By example NgClass Example Conditionally apply class Angular ngStyle Directive Angular Trackby to improve ngFor Performance How to Create & Use Custom Directive In Angular Working with Angular Pipes How to Create Custom Pipe in Angular Formatting Dates with Angular Date Pipe Using Angular Async Pipe with ngIf & ngFor angular keyValue pipe Using Angular Pipes in Components or Services Angular Component Communication & Sharing Data Angular Pass data to child component Angular Pass data from Child to parent component Component Life Cycle Hooks in Angular Angular ngOnInit And ngOnDestroy Life Cycle hook Angular ngOnChanges life Cycle Hook Angular ngDoCheck Life Cycle Hook Angular Forms Tutorial: Fundamentals & Concep t s Angular Template-driven forms example How to set value in template-driven forms in Angular Angular Reactive Forms Example Using Angular FormBuilder to build Forms SetValue & PatchValue in Angular StatusChanges in Angular Forms ValueChanges in Angular Forms FormControl in Angular FormGroup in Angular Angular FormArray Example Nested FormArray Example Add Form Fields Dynamically SetValue & PatchValue in FormArray Angular Select Options Example in Angular Introduction to Angular Services Introduction to Angular Dependency Injection Angular Injector, @Injectable & @Inject Angular Providers: useClass, useValue, useFactory & useExisting Injection Token in Angular How Dependency Injection & Resolution Works in Angular Angular Singleton Service ProvidedIn root, any & platform in Angular @Self, @SkipSelf & @Optional Decorators Angular '@Host Decorator in Angular ViewProviders in Angular Angular Reactive Forms Validation Custom Validator in Angular Reactive Form Custom Validator with Parameters in Angular Inject Service Into Validator in Angular template_driven_form_validation_in_angular Custom Validator in Template Driven Forms in Angular Angular Async Validator Example Cross Field or Multi Field Validation Angular How to add Validators Dynamically using SetValidators in Angular Angular HttpClient Tutorial & Example Angular HTTP GET Example using httpclient Angular HTTP POST Example URL Parameters, Query Parameters, httpparams in Angular HttpClient Angular HTTPHeaders Example Understanding HTTP Interceptors in Angular Angular Routing Tutorial with Example Location Strategy in Angular Angular Route Params Angular : Child Routes / Nested Route Query Parameters in Angular Angular Pass Data to Route: Dynamic/Static RouterLink, Navigate & NavigateByUrl to Navigate Routes RouterLinkActive in Angular Angular Router Events ActivatedRoute in Angular Angular Guards Tutorial Angular CanActivate Guard Example Angular CanActivateChild Example Angular CanDeactivate Guard Angular Resolve Guard Introduction to Angular Modules or ngModule Angular Routing between modules Angular Folder Structure Best Practices Guide to Lazy loading in Angular Angular Preloading Strategy Angular CanLoad Guard Example Ng-Content & Content Projection in Angular Angular @input, @output & EventEmitter Template Reference Variable in Angular ng-container in Angular How to use ng-template & TemplateRef in Angular How to Use ngTemplateOutlet in Angular '@Hostbinding and @Hostlistener_in_Angular Understanding ViewChild, ViewChildren &erylist in Angular ElementRef in Angular Renderer2 Example: Manipulating DOM in Angular ContentChild and ContentChildren in Angular AfterViewInit, AfterViewChecked, AfterContentInit & AfterContentChecked in Angular Angular Decorators Observable in Angular using RxJs Create observable from a string, array & object in angular Create Observable from Event using FromEvent in Angular Using Angular observable pipe with example Angular Map Operator: Usage and Examples Filter Operator in Angular Observable Tap operator in Angular observable Using SwitchMap in Angular Using MergeMap in Angular Using concatMap in Angular Using ExhaustMap in Angular Take, TakeUntil, TakeWhile & TakeLast in Angular Observable First, Last & Single Operator in Angular Observable Skip, SkipUntil, SkipWhile & SkipLast Operators in Angular The Scan & Reduce operators in Angular DebounceTime & Debounce in Angular Delay & DelayWhen in Angular Using ThrowError in Angular Observable Using Catcherror Operator in Angular Observable ReTryWhen inReTry, ReTryWhen in Angular Observable Unsubscribing from an Observable in Angular Subjects in Angular ReplaySubject, BehaviorSubject & AsyncSubject in Angular Angular Observable Subject Example Sharing Data Between Components Angular Global CSS styles View Encapsulation in Angular Style binding in Angular Class Binding in Angular Angular Component Styles How to Install & Use Angular FontAwesome How to Add Bootstrap to Angular Angular Location Service: go/back/forward Angular How to use APP_INITIALIZER Angular Runtime Configuration Angular Environment Variables Error Handling in Angular Applications Angular HTTP Error Handling Angular CLI tutorial ng new in Angular CLI How to update Angular to latest version Migrate to Standalone Components in Angular Create Multiple Angular Apps in One Project Set Page Title Using Title Service Angular Example Dynamic Page Title based on Route in Angular Meta service in Angular. Add/Update Meta Tags Example Dynamic Meta Tags in Angular Angular Canonical URL Lazy Load Images in Angular Server Side Rendering Using Angular Universal The requested URL was not found on this server error in Angular Angular Examples & Sample Projects Best Resources to Learn Angular Best Angular Books in 2020

Angular ngOnChanges life Cycle Hook

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.

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.

                              
 
@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.

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

                              
 
{
  "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}
}
                            
                        

ngOnChanges example

Create a class customer.ts under src/app folder.

                              
 
export class Customer {
  code: number;
  name: string;
}
                            
                        

Parent Component

                              
 
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;
  }
}
                            
                        

Child Component

                              
 
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

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

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

Source Code

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