Constructor
- The Constructor is a default method of the class that is executed when the class is instantiated.
- Constructor ensures proper initialization of fields (class members) in the class and its subclasses.
- Angular Dependency Injector (DI) analyse the constructor parameters.
- When we call new MyClass() it creates a new instance of the class.
- While calling new MyClass() we must have to pass the exact match of the parameters type to the constructor of the class, example:
- new MyClass(arg1:number, arg2:string, argN:any)
- These arg1:number, arg2:string, argN:any, must be of same type defined in constructor of class MyClass.
ngOnInit
- ngOnInit is a life cycle hook called by Angular to indicate that the Angular is done creating the component.
- ngOnInit does not take any parameter.
- In order to use OnInit we have to import it in the component class like this:
- import {Component, OnInit} from ‘@angular/core’;
- Actually, implementing OnInit in every component is not mandatory. But considered good practice.
- A class implements OnInit like this: export class AppComponent implements OnInit { }
Difference between ngOnInit() and constructor()
- We use constructor() for all the initialization/declaration.
- It’s better to avoid writing actual work in the constructor.
- The constructor() should only be used to initialize class members but shouldn’t do actual “work”.
- So, we should use constructor() to setup Dependency Injection, Initialization of class fields etc.
- ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated.
- Like loading data from Database — to show the user in your HTML template view. Such code should be written in ngOnInit().