fbpx Skip to content

Aquent | DEV6

When to use ngOnInit and constructor in Angular 2 components

Written by: Geoffrey Chan

TL;DR

Use the constructor to initialize class members and for dependency injection. Use ngOnInit for initialization work.

At first look it can be hard to know when to use the ngOnInit and constructor methods, especially if you’re coming from Angular 1 development. Both methods are similar in that they are called when the component is created. However, knowing when and how to use them are important in understanding how to best structure your component’s code.

First, let’s take a look at the constructor method.

export class AppComponent {

                  constructor() {}

}

The constructor method is not actually an Angular 2 method. It is a predefined method in a TypeScript class which is called when the class is instantiated. The constructor’s purpose is to help prepare the creation of a new instance of the class. In the context of Angular 2 it can be used to properly initialize fields. Angular 2’s DI (dependency injection) also tries to find providers that match the types of the constructor’s parameters, resolves them, and passes them to the constructor as arguments.

export class AppComponent {

                  constructor(myService: MyService) {

                  this.samples = myService.getSamples();

                  this.sentence = ‘This is my constructor example.’;

}

}

The result of myService.getSample() will get saved to this.samples once it is resolved, and this.sentence will be initialized with the string ‘This is my constructor example.’.

Now let’s take a look at ngOnInit. First we have to import OnInit.

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

Then we implement it in order to use it in the class. The class we import is called OnInit but the method we use is called ngOnInit(). This was a point of confusion for me because I thought that the method name was OnInit().

export class AppComponent implements OnInit {

                  export class AppComponent {

                  constructor(myService: MyService) {

                  this.samples = myService.getSamples();

                  this.sentence = ‘This is my constructor example.’;

}

}

 

ngOnInit() {}

}

So what do we actually do in the ngOnInit method? The Angular docs gives us a definition:

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component’s input properties.

The ngOnInit method runs after the constructor method, meaning that all of the injected dependencies will be resolved and all of the class members will be defined. This makes it the perfect place to do any of the initialization work/logic for the component.

Let’s put it all together and see them both in action:

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

 

export class AppComponent implements OnInit {

                  constructor(myService: MyService) {

//Let’s assume this will return an array of samples [‘sample 1’, ‘sample 2’, ‘sample 3’]

                  this.samples = myService.getSamples();

                  this.sentence = ‘Number of samples: ’;

}

 

ngOnInit() {

                  this.countSamples();

}

 

countSamples() {

//Result will be ‘Number of samples: 3’

                  this.sentence = this.sentence + this.samples.length;

}

}

In this example we are injecting the dependency myService. You should not confuse this with MyService (note the uppercase ‘M’) which is the type of the service. Then we are calling the method myService.getSamples() which will resolve with an array. In our ngOnInit() method we call the function this.countSamples() which is able to work with the (already initialized and resolved) fields this.samples and this.sentence. We can see that countSamples() simply appends the length of this.samples to the string this.sentence.

Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

View Course Details