What is ngOnInit?

What is ngOnInit?

When you create a new component, you will realize that a method named ngOnInit ( ) appears below the constructor:

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

@Component ({
selector :’app-home’,
templateUrl:’./home.component.html’,
styleUrls:[‘./home.component.css’]
})
export class HomeComponent implements OnInit{

constructor(){}ngOnInit{

}
}

Every component has a lifecycle. The ngOnInit() method is called immediately after Angular finishes setting up the component.

What we can do inside the ngOnInit() method is that some operations like fetching data, or something we want to see immediately on page load. It is not recommended to do these kinds of operations inside the constructor, so we have ngOnInit instead.

In Angular, the constructor should only be responsible for dependency injection.

we need ngOnInit() method for:

1. To perform complex initializations shortly after construction.
2. To set up the component after Angular sets the input properties.

An ngOnInit() is a good place for a component to fetch its initial data.

By in on Jan 07 2020
• Jan, 2020 10

ngOnInit is mainaly used for initialization data in component, this is best place to give call to service , this event raise after ngOnChance(), ngOnInit is called only one time in life component life cycle.

• 2
• May, 2020 30

ngOnInit() is Lifecycle Method in Angular component allows you to run piece of code at different stages of life of component.

• 1
• May, 2020 9

ngOnint is a life cycle hook event and is used to initialize the directive or component. It sets data bound properties. In Angular there are 8 life cycle hooks.

• 1
• Jan, 2020 28

Called once the component initialized

• 1
• Jan, 2020 9

we use constructor to do the DI(Dependency Injection) for us, while in Angular 1 it was happening through calling to String method and checking which dependency was injected.

As you see in the above diagram, ngOnInit is happening after the constructor is ready and ngOnChnages and get fired after the component is ready for us. All initialisation can happen in this stage, a simple sample is injecting a service and initials it on init.

OK, I also share a sample code for you to look, see how we get use of ngOnInit and constructor in the code below:

import { Component, OnInit } from ‘@angular/core’;
import { Router } from ‘@angular/router’;

@Component({
selector: ‘my-app’,
template: <h1>App is running!</h1><my-app-main [data]=data></<my-app-main>,
styles: [‘h1 { font-weight: normal; }’]
})
class ExampleComponent implements OnInit {
constructor(private router: Router) {} //Dependency injection in the constructor

// ngOnInit, get called after Component initialised!
ngOnInit() {
console.log(‘Component initialised!’);
}
}

• 1
• Jun, 2020 21

It is called by Angular for indicating the initialization of the component.

• 0