Angular ngOnChanges lifecycle event

 You need to create a small component if you are working on a large enterprise application. Small components are more flexible in both maintainability and reusability. When you create small, child components, you need to pass the data each time whenever you update them from an API. Angular provides fabulous assistance with error handling using it RxJs library and this adds value to the Angular popularity.

What is Angular Lifecycle?

  • The components are the main building block for every application in Angular. Each component has a lifecycle, a process of creating and executing all the functions, then destroying instances during execution.
  • The component lifecycle consists of eight different stages.   These are called life cycle events.   We can use this event at various stages of any application to control the components.
  • Below is the lifecycle sequence available in the order in which they are called.

 

  • ngOnChanges()
  • ngOnInit()
  • ngDoCheck()
  • ngAfterContentInit()
  • ngAfterContentChecked()
  • ngAfterViewInit()
  • ngAfterViewChecked()
  • ngOnDestroy()

ngOnChanges():

  • ngOnChanges event is executed each time whenever the value of the input control in the component has been modified. It is used to detect modifications of input properties in angular programming. We can use this lifecycle event to respond to the changes in our @Input () variables. ngOnChanges event is called before the ngOnInit() event.
  • You need to import OnChanges from the @angular/core library to use the ngOnChanges event.

 

import { Component, SimpleChanges } from ‘@angular/core’;

import { OnChanges } from ‘@angular/core’;

 

@Component({

selector: ‘app-root’,

templateUrl: ‘./app.component.html’,

styleUrls: [ ‘./app.component.scss’ ]

})

export class AppComponent implements OnChanges {

title = ‘Demo-ngOnChanges’;

ngOnChanges( changes: SimpleChanges ): void {

throw new Error( ‘Method not implemented.’ );

}

}

 

  • All @Input properties in our component are given a SimpleChange object (if the property is modified). SimpleChanges is the object which holds the instance of the SimpleChange object. These SimpleChanges objects are accessible using the @Input property name for the key.

SimpleChange:

It is a simple class that has three properties.

[ 1] previousValue: any -> The preceding value of the input property.

[ 2] currentValue: any -> The new or present value for the input property.

[ 3] firstChange(): boolean -> Boolean value, that tells us if it was the first time the change has occurred.

  • For example, if both test1 and test2 input properties are changed, then the SimpleChanges object looks like.

 

{

“test1”: { “previousValue” : “oldvalue”,

“currentValue” : “newvalue”,

“firstChange” : false

},

“test2”: { “previousValue” : “oldvalue”,

“currentValue” : “newvalue”,

“firstChange” : false

}

}

 

  • If the input property is an object (employee name and code property), then the SimpleChanges looks like.

 

{

“Employee”:

{

“previousValue”: { “name” : “Keval”, “code”:”15″ },

“currentValue”: { “name” : “Vatsal”, “code”:”25″ },

“firstChange” : false }

}

}

 

ngOnChanges vs ngOnInit:

ngOnInit is called only once during component initialization. ngOnChanges event is executed each time whenever the value of the input control in the component has been modified. ngOnChanges event is called before the ngOnInit() event.

ngOnChanges example:

  • In this example, we have a child component named childComponent and another component is a parent component named the appcomponent.

First, create a class employee.ts in the app folder.

 

export class Employee {

empname: string;

empsalary: number;

}

 

  • In the app.module.ts file, import the forms module from the ‘@angular/forms’ library.

import { BrowserModule } from ‘@angular/platform-browser’;

import { NgModule } from ‘@angular/core’;

import { AppRoutingModule } from ‘./app-routing.module’;

import { AppComponent } from ‘./app.component’;

import { ChildComponent } from ‘./child/child.component’;

import { FormsModule } from ‘@angular/forms’;

@NgModule({

declarations: [

AppComponent,

ChildComponent

],

imports: [

BrowserModule,

AppRoutingModule,

FormsModule

],

providers: [],

bootstrap: [ AppComponent ]

})

export class AppModule { }

 

  • In the parent component (app.component.ts) file, create the updateEmployee method to update the value of the employee.

import { Component, SimpleChanges } from ‘@angular/core’;

import { OnChanges } from ‘@angular/core’;

import { Employee } from ‘../app/employee’;

 

@Component({

selector: ‘app-root’,

templateUrl: ‘./app.component.html’,

styleUrls: [ ‘./app.component.scss’ ]

})

export class AppComponent implements OnChanges {

title = ‘Demo-ngOnChanges’;

ngOnChanges( changes: SimpleChanges ): void {

throw new Error( ‘Method not implemented.’ );

}

 

message = ”;

employee: Employee = new Employee();

name= ”;

salary= 0;

updateEmployee() {

this.employee.empname = this.name;

this.employee.empsalary = this.salary;

}

}

 

  • In the app.component.html file, add the following code.

<h1> {{title}}! </h1>

<p> Message : <input type=’text’ [(ngModel)]=’message’> </p>

<p> Salary : <input type=’number’ [(ngModel)]=’salary’> </p>

<p> Name : <input type=’text’ [(ngModel)]=’name’> </p>

<p> <button (click) = “updateEmployee()”> Update </button> </p>

<app-child [message] = message [employee] = employee> </app-child>

In this code, we have three input fields: message, name, and salary. The update employee button updates the value of the Employee object.

The employee and message are bounded to the child component using the property binding.

<app-child [message] = message [employee] = employee> </app-child>

 

  • In the child.component.ts file, first we need to import Input, OnInit, OnChanges, SimpleChanges from the angular core.

import { Component, Input, OnChanges, OnInit, SimpleChanges } from ‘@angular/core’;

import { Component, Input, OnChanges, OnInit, SimpleChanges } from ‘@angular/core’;

import { Employee } from ‘../employee’;

 

@Component({

selector: ‘app-child’,

templateUrl: ‘./child.component.html’,

styleUrls: [‘./child.component.scss’]

})

export class ChildComponent implements OnInit, OnChanges {

constructor() { }

ngOnInit(): void {

}

@Input() message: string;

@Input() employee: Employee;

changelog: string[] = [];

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

}

}

}

 

  • The child component implements the onInit and onChanges life cycle events. We can also declare the employee and message property that we decorate with the @Input decorator. The parent component updates those properties using the property binding. The ngOnChanges event receives all the modifications as an instance of the SimpleChanges.

 

  • In the child.component.html file, add the following code.

<h2> Child  Component </h2>

<p> Message: {{ message }} </p>

<p> Employee Name: {{ employee.empname }} </p>

<ul>

<li *ngFor=”let log of changelog;”> {{ log }} </li>

</ul>

 

Conclusion

In this blog, we have seen what is Angular lifecycle and different types of lifecycle events in Angular. We have seen the ngOnChanges event. ngOnChanges event is executed each time whenever the value of the input control in the component has been modified.

Author Bio: Kapil Panchal – Digital Marketing Manager 

I am working as a Digital Marketing Manager iFour Technolab Pvt. Ltd. Being a technical writing enthusiast and a goal-oriented individual with honed communication skills, I have served in the Information technology, Services, and Product industry. Having a high-energy level, I absolutely love what I do and I’m passionate about being better every day. Hire our Angular developers to address your business concerns using Angular technology.

Leave a reply:

Your email address will not be published.

Site Footer

{"wp_error":"cURL error 60: SSL certificate problem: unable to get local issuer certificate"}