Sharing Top Content from the Angular-sphere.

The essential difference between Constructor and ngOnInit in Angular

  • ngOnInit is just a method on a class which structurally is not different to any other method on a class.
  • It’s just that Angular team decided to name it that way but it could have been any other name:class MyComponent { ngOnInit() { } otherNameForNgOnInit() { }}And it’s completely up to you if you want to implement that method or not on a component class.
  • During compilation Angular compiler checks whether a component has this method implemented and marks the class with an appropriate flag:export const enum NodeFlags { … OnInit = 1 16,This flag is then used to decide whether to call the method on a component class instance or not during change detection:if…
  • Regardless whether you implement it or not in TypeScript class it’s still will be called when creating an instance of a class.
  • This is because a typescript class constructor is transpiled into a JavaScript constructor function:class MyComponent { constructor() { console.log(‘Hello’); }}transpiled intofunction MyComponent() { console.log(‘Hello’);}To create a class instance this function is called with the new operator:const componentInstance = new MyComponent(So if you omit the constructor in a class, it’s transpiled…

One of the most popular Angular questions on stackoverflow is Difference between Constructor and ngOnInit with over 100k views. I gave my answer to this question there but also decided to expand on…

One of the most popular Angular questions on stackoverflow is Difference between Constructor and ngOnInit with over 100k views. I gave my answer to this question there but also decided to expand on it in this article. While most answers in the thread and articles on the web focus on the difference between the usage of the two here I’d like to give a more comprehensive comparison that taps into components initialization process.

is just a method on a class which structurally is not different to any other method on a class. It’s just that Angular team decided to name it that way but it could have been any other name:

And it’s completely up to you if you want to implement that method or not on a component class. During compilation Angular compiler checks whether a component has this method implemented and marks the class with an appropriate flag:

This flag is then used to decide whether to call the method on a component class instance or not during change detection:

A constructor in turn is a different thing. Regardless whether you implement it or not in TypeScript class it’s still will be called when creating an instance of a class. This is because a typescript class constructor is transpiled into a JavaScript constructor function:

console.log(‘Hello’);

transpiled into

operator:

So if you omit the constructor in a class, it’s transpiled into an empty…

The essential difference between Constructor and ngOnInit in Angular