I think the best example would be using services. Let's say that I want to grab data from my server when my component gets 'Activated'. Let's say that I also want to do some additional things to the data after I get it from the server, maybe I get an error and want to log it differently.
It is really easy with ngOnInit over a constructor, it also limits how many callback layers I need to add to my application.
with my constructor I could just call my _userService and populate my user_list, but maybe I want to do some extra things with it. Like make sure everything is upper_case, I am not entirely sure how my data is coming through.
It makes it much easier to see, and so I just call my function within my component when I initialize instead of having to dig for it somewhere else. Really it's just another tool you can use to make it easier to read and use in the future. Also I find it really bad practice to put function calls within a constructor!
The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better Dependency Injector (DI) analyzes the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like
new MyClass(someArg);
ngOnInit is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.
We have to import OnInit in order to use like this (actually implementing OnInit is not mandatory but considered good practice):
import {Component, OnInit} from '@angular/core';
then to use the method of OnInit we have to implement in the class like this.
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized.
ngOnInit is called right after the directive's data-bound properties have been checked for the first time,
and before any of its children have been checked.
It is invoked only once when the directive is instantiated.
Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".
So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.
Constructor : constructor is a default method runs (by deafult) when component is being constructed. When you create an instance of a class that time also constructor(default method) would be called. So in other words, when component is being constructed or/and an instance is created constructor(default method) is called and relevant code written within is called. Basically and generally in Angular2 it used to inject things like services when component is being constructed for the further use.
OnInit: ngOnInit is component's life cycle hook which runs first after constructor(default method) when component is being initialized.
So, Your constructor will be called first and Oninit will be called later after constructor method.
boot.ts
import {Cmomponent, OnInit} from 'angular2/core';
import {ExternalService} from '../externalService';
export class app implements OnInit{
constructor(myService:ExternalService)
{
this.myService=myService;
}
ngOnInit(){
// this.myService.someMethod()
}
}
OK, first of all ngOnInit is part of Angular lifecycle, while constructor is part of ES6 JavaScript class, so the major difference starts from right here!...
Look at the below chart I created which shows the lifecycle of Angular.
In Angular2+ 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!');
}
}
Like a lot of other languages, you can initialize variables at the class level, the constructor, or a method. It is up to the developer to decide what is best in their particular case. But below are a list of best practices when it comes to deciding.
Class level variables
Usually, you will declare all your variables here that will be used in the rest of you component. You can initialize them if the value doesn't depend on anything else, or use const keyword to create constants if they will not change.
export class TestClass{
let varA: string = "hello";
}
Constructor
Normally it's best practice to not do anything in the constructor and just use it for classes that will be injected. Most of the time your constructor should look like this:
this will automatically create the class level variables, so you will have access to customService.myMethod() without having to do it manually.
NgOnInit
NgOnit is a lifecycle hook provided by the Angular 2 framework. Your component must implement OnInit in order to use it. This lifecycle hook gets called after the constructor is called and all the variables are initialized. The bulk of your initialization should go here. You will have the certainty that Angular has initialized your component correctly and you can start doing any logic you need in OnInit versus doing things when your component hasn't finished loading properly.
Here is an image detailing the order of what gets called:
If you are using Angular 2 framework and need to interact with certain lifecycle events, use the methods provided by the framework for this to avoid problems.
I think the best example would be using services. Let's say that I want to grab data from my server when my component gets 'Activated'. Let's say that I also want to do some additional things to the data after I get it from the server, maybe I get an error and want to log it differently.
It is really easy with ngOnInit over a constructor, it also limits how many callback layers I need to add to my application.
For Example:
with my constructor I could just call my _userService and populate my user_list, but maybe I want to do some extra things with it. Like make sure everything is upper_case, I am not entirely sure how my data is coming through.
So it makes it much easier to use ngOnInit.
It makes it much easier to see, and so I just call my function within my component when I initialize instead of having to dig for it somewhere else. Really it's just another tool you can use to make it easier to read and use in the future. Also I find it really bad practice to put function calls within a constructor!
The
Constructor
is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better Dependency Injector (DI) analyzes the constructor parameters and when it creates a new instance by callingnew MyClass()
it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor likengOnInit
is a life cycle hook called by Angular2 to indicate that Angular is done creating the component.We have to import
OnInit
in order to use like this (actually implementingOnInit
is not mandatory but considered good practice):then to use the method of
OnInit
we have to implement in the class like this.Mostly we use
ngOnInit
for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".So you should use
constructor()
to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.For more information refer here:
https://angular.io/api/core/OnInit
Angular 2 Component Constructor Vs OnInit
Short and simple answer would be,
Constructor
:constructor
is adefault method
runs (by deafult) when component is being constructed. When you createan instance
of a class that time alsoconstructor(default method)
would be called. So in other words, when component is beingconstructed or/and an instance is created constructor(default method)
is called and relevant code written within is called. Basically and generally inAngular2
it used to inject things likeservices
when component is being constructed for the further use.OnInit
: ngOnInit is component's life cycle hook which runs first afterconstructor(default method)
when component is being initialized.So, Your constructor will be called first and Oninit will be called later after constructor method.
boot.ts
Resources: LifeCycle hook
You can check this small demo which shows implementation of both things.
OK, first of all
ngOnInit
is part of Angular lifecycle, whileconstructor
is part of ES6 JavaScript class, so the major difference starts from right here!...Look at the below chart I created which shows the lifecycle of Angular.
In Angular2+ we use
constructor
to do theDI(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 andngOnChnages
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
andconstructor
in the code below:Two things to observe here:
Both have different usability.
Like a lot of other languages, you can initialize variables at the class level, the constructor, or a method. It is up to the developer to decide what is best in their particular case. But below are a list of best practices when it comes to deciding.
Class level variables
Usually, you will declare all your variables here that will be used in the rest of you component. You can initialize them if the value doesn't depend on anything else, or use const keyword to create constants if they will not change.
Constructor
Normally it's best practice to not do anything in the constructor and just use it for classes that will be injected. Most of the time your constructor should look like this:
this will automatically create the class level variables, so you will have access to
customService.myMethod()
without having to do it manually.NgOnInit
NgOnit is a lifecycle hook provided by the Angular 2 framework. Your component must implement
OnInit
in order to use it. This lifecycle hook gets called after the constructor is called and all the variables are initialized. The bulk of your initialization should go here. You will have the certainty that Angular has initialized your component correctly and you can start doing any logic you need inOnInit
versus doing things when your component hasn't finished loading properly.Here is an image detailing the order of what gets called:
https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html
TLDR
If you are using Angular 2 framework and need to interact with certain lifecycle events, use the methods provided by the framework for this to avoid problems.