Angular — When to use the constructor() versus the ngOnInit() method?

Abraham Joseph
2 min readJul 6, 2021

At first lets understand what constructor() and ngOnInit() is and the major difference.

constructor() { }

A constructor is not the concept of Angular. It is the concept of JavaScript’s class. When you initialize the class the constructor will call every time.

The constructor function comes with every class, constructors are not specific to Angular but are concepts derived from Object oriented designs. The constructor creates an instance of the component class.

ngOnInit() { }

Every component we create in Angular has a component life cycle. The ngOnInit function is one of an Angular component’s life-cycle methods.

The ngOnInit method is called shortly after the component is created.

Now coming to the point,

The constructor() method is invoked in the first step. Component Lifecycle Hooks are methods on Component or Directive that Angular calls at a specific moment of the change detection process. The ngOnInit() method is the second at this lifecycle sequence. It is called once and means that the object is ready to use because Angular already set all input properties and displayed the data-bound properties.

The code added to the constructor is always initialized before the ngOnInit() method. We typically use the constructor to Inject Dependencies. Also, practical experience says — the less logic in the constructor the better. Moreover, remember that input binding is not available in constructor considering the change detection and the Input communication mechanism. The ngOnInit is a great place to add logic for a component that is outside of Dependency Injection, Input Binding, DOM, Router ecosystem. ngOnInit() is a better place to write “actual work code” that we need to execute as soon as the class is instantiated.

Let’s simply conclude :

Constructor initializes class members.

ngOnInit() is a place to put the code that we need to execute at very first as soon as the class is instantiated.

--

--

Abraham Joseph

I design and develop experience that makes peoples life simple.