Skip to main content

constructor vs ngOnInit in Angular

2 min read

Older Article

This article was published 8 years ago. Some information may be outdated or no longer applicable.

If you’ve looked at an Angular2+ component, you’ve seen both constructor() and ngOnInit(). Let’s pull apart the differences and understand why they both exist.

Example code

Here’s what a freshly generated component from the Angular CLI looks like (you can create one with ng generate component):

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

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})
export class MyComponentComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

The constructor

The constructor() has nothing to do with Angular. TypeScript (and ES2015 JavaScript) supports classes, and classes have constructors.

The JavaScript engine invokes it. Angular doesn’t.

ngOnInit

ngOnInit() is one of Angular’s lifecycle hooks. A lifecycle hook lets you tap into different stages of a component’s life. Angular calls ngOnInit() after it’s finished creating the component.

When to use constructor and ngOnInit?

Now you can see how they’re different, and each fits a different job.

Here’s the rule of thumb: use constructor() for dependency injection. Wire up the dependencies your component needs.

import { HttpClient } from '@angular/common/http';
// ...
constructor(private http: HttpClient) { }

ngOnInit gets called after Angular has created the component, loaded its dependencies, placed it in the DOM, and processed all input bindings. That means input values are accessible inside ngOnInit but not inside the constructor:

// given that the component is called via: <app-my-component [user]="user"></app-my-component>
export class MyComponentComponent implements OnInit {
  @Input()
  user: any;
  constructor() {
    console.log(this.user); // undefined
  }

  ngOnInit() {
    console.log(this.user); // { username: "John", age: 33 }
  }
}