How do we use ngOnInit and constructor in Angular 2 components

Constructor is use for class members and for dependency injection in Angular 2. ngOnInit is use for initialization.

When component is created both ngOnInit and constructor is called.

But is good to know where and how we used ngOnInit and constructor in Angular 2 components.

Constructor :-


export class AppComponent {

constructor() {}

}

The Constructor is predefined method of typescript which is called when the class is instantiated.
A Constructor is a special type of method of a class and it will be automatically invoked when an instance of the class is created.In Angular 2 it can be used to initialize fields and dependency injection look into following example :-


constructor(heroService: HeroService) {
this.heroes = heroService.getHeroes();
}

constructor parameter has the type HeroService and its tell the Angular injector to inject an instance of HeroService whenever it creates a new Component.

ngOnInit :-

First need to import OnInit in component.


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

The class we import is called OnInit but the method we use is called ngOnInit().


export class AppComponent implements OnInit {
constructor(heroService: HeroService) {
this.heroes = heroService.getHeroes();
}
ngOnInit() {}
}

According to Angular Docs

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.

The ngOnInit method runs after the constructor method.

Final Example :-


import {Component, OnInit} from '@angular/core';
export class AppComponent implements OnInit {

 constructor(heroService: HeroService) {
   this.heroes = heroService.getHeroes(); // return ["Iron Man", "Spiderman", "Arrow", "Batman"]
 }

 ngOnInit() {
   this.countHeroes();
 }

 countHeroes() {
   this.heroCount = this.heroes.length; // return 4
 }
}

In this example we inject the dependency heroService. Then we are calling the method heroService.getHeroes() which will return array. In ngOnInit() method we call the function this.countHeroes() and countHeroes() is able to get the (already initialized and resolved) field this.heroes and return this.heroes length (4).

Leave a Reply

Your email address will not be published. Required fields are marked *