Angular 2 OnInit vs OnChanges




Asked on January 24, 2017
What is difference between Angular 2 OnInit and OnChanges and how to use them?


Replied on July 26, 2018
Find the difference between OnInit and OnChanges

OnInit

OnInit interface is a lifecycle hook. It has a method ngOnInit(). It is called after data-bound properties of component/directive are initialized. ngOnInit() is called only once. In the lifecycle sequence, ngOnInit() is called just after first ngOnChanges() call. OnInit can be implemented by component, directive, pipe etc. ngOnInit() can be used for following purposes. 

1. Perform complex initialization in ngOnInit() and not in constructor. 

2. If we need to fetch data then it should be done in ngOnInit() and not in constructor so that we should not worry while initializing component. A constructor should perform only local variable initialization. 

For the example a component will implement OnInit as following.

@Component({
   ---
})
export class CounterComponent implements OnInit { 
  ngOnInit() {
    ---
  }
  ---
}





OnChanges

OnChanges is a lifecycle hook that is called when any data-bound property of a directive changes. OnChanges is an interface that has a method declaration as follows.

ngOnChanges(changes: SimpleChanges)

A component that needs to detect changes in its data-bound property of a directive, has to implement OnChanges interface and override its ngOnChanges() method. It has the argument as SimpleChanges that is used to get new and previous values of input property. They are used as follows.

import {Component, OnChanges, SimpleChanges, Input} from '@angular/core';

import { Employee } from './employee';
 
@Component({
  selector: 'app-emp',
  templateUrl: './employee.component.html'
})
export class EmployeeComponent implements OnChanges {
  @Input() employee: Employee;
  @Input() message: string;

  ngOnChanges(changes: SimpleChanges) {
     for (let propName in changes) {  
let change = changes[propName];
let curVal  = JSON.stringify(change.currentValue);
let prevVal = JSON.stringify(change.previousValue);

        console.log(curVal);
        console.log(prevVal);
     }
  }
}





Write Answer










©2024 concretepage.com | Privacy Policy | Contact Us