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{
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:
An ngOnInit() is a good place for a component to fetch its initial data.
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.
ngOnInit() is Lifecycle Method in Angular component allows you to run piece of code at different stages of life of component.
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.
Called once the component initialized
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
<h1>App is running!</h1><my-app-main [data]=data></<my-app-main>
// ngOnInit, get called after Component initialised! ngOnInit() { console.log(‘Component initialised!’); }}
For more follow the linkhttps://www.angularjswiki.com/angular/what-is-the-difference-between-constructor-and-ngoninit-in-angular/
It is called by Angular for indicating the initialization of the component.