Home Angular Tutorials Angular ngOnInit lifecycle hook

Angular ngOnInit lifecycle hook

by aouidane.med.amine
78,986 views 15 min read

In this tutorial, we will learn the ngOnInit lifecycle hook in angular, we will also see how and when we use it through a basic example step by step.

Table of Contents

Angular Lifecycle Hooks

Generally, the angular lifecycle hook is a simple function callback that angular invokes when a specific event occurs during the component life cycle. 

Angular has 8 lifecycle hooks, but in this tutorial we will cover only the ngOnInit lifecycle hook.

ngOnInit lifecycle hook Syntax and usage note :

				
					@Component({selector: 'my-cmp', template: `...`})
class MyComponent implements OnInit {
  ngOnInit() {
    // ...
  }
}
				
			

Source : angular.io

what is ngOnInit lifecycle hook in angular ?

Every component that we create in our project , angular controls the life cycle hook of that component.

ngOnInit hook for example is called by Angular when the component is initialized , that means , after it creates the component and updates the inputs properties and before any of the view and child view have been checked.

ngOninit lifecycle hook is invoked only one time, that is why it’s the best place to put all your initialization logic, especially in the Child component that using inputs() because you have access to every input property of your component.

what should i use: ngOnInit or Constructor() ?

You can’t use the ngOninit lifecycle hook like a constructor, there is a big difference between them.

The constructor is only used to initialize the class members and inject your dependencies into the component class ( services , Http .. )  that will be used in the ngOninit hook to manipulate your data and build your application logic ( get data from Api , save data … )

In our example, we will create a child component that accepts an Input() used to pass the data from the parent.

With this example, we will see how to implement the ngOnInit() lifecycle hook, and we will check exactly  when the OnInit lifecycle hook is invoked  and the difference between ngOninit and the constructor.

How to use ngOnInit lifecycle hook ?

Parent component : app-component.ts

				
					import { Component} from '@angular/core';

import { ChildComponent } from './child-component/child.component';
@Component({
  selector: 'app-root',
  template: '<app-child  [user]="user"></app-child>'
  styleUrls: ['./app.component.scss']
})
export class AppComponent{
   user = {
    name:"XperTuto"
  }
}

				
			

As we said, ngOnInit hook is a simple function callback, so to use it in our project we need to import it in our class :

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

child-component.ts

				
					
import { Component, OnInit, Input} from '@angular/core';
@Component({
  selector: 'app-child',
  template: `<div> Here is the user name: {{ user.name }}</div>`,
})
export class ChildComponent implements OnInit {

// the value that was injected from the parent is : XperTuto
 @Input() user : any ;

  constructor() {
      console.log("[constructor] data from Parent : " + this.user?.name)
  }

  ngOnInit() {
    console.log("[ngOnInit] data from Parent : " + this.user?.name)
  }
}

				
			

When we run the application, we will have the following log :  

[constructor] data from Parent : undefined

[ngOnInit] data from Parent : XperTuto

As you see, we can’t access the @input() from the constructor event if it was called before the ngOnInit by angular, because the @Input() property is not initialized if the component view is not set up yet, which will not happen at the moment of the constructor invocation.

That’s why we get “undefined” when we want to access to the Input() value from the constructor().

So the best place to get the data of the @Input() is the OnInit() lifecycle hook,

it’s invoked when everything in your component was completely initialized.

Recapitulation

In this tutorial we have seen multiples use cases of ngOnInit lifecycle hook in Angular also we have seen the difference between the ngOnInit() and the constructor() through a basic example to avoid any confusion between them.

Clone and Run the project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/ngOnInit_lifecycle_hook.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Lifecycle hooks:

You may also like