Karl Gorman
03
June
2021
NgOnInit and Constructor methods In Angular

Main Differences Between NgOnInit and Constructor methods In Angular

Angular, a popular platform meant to develop robust applications, defines the number of lifecycle functions. As it is the response function of the event, the use of Angular constructor and ngOnInit plays a significant role in developing applications. However, the terms often confuse a Angular developer, especially if one is new to Angular. Both constructor and ngOnInit in Angular are available lifecycle hooks that provide extensive benefits to developers in the process of application development. While the Angular component constructor helps accomplish a substantial amount of work during class initialization, the use of ngOnInit, on the other hand, depends on the type of task. Let’s dive deep into the concept of ngOnInit vs constructor for better understanding.

promo image3
Looking for a new challenge?

Interesting projects

Friendly team

Decent payment

What is an Angular Constructor?

As a part of class-based object-oriented programming, constructor refers to a special type of method used to create an object. It is significantly put into use for initializing the class and its subclasses. A class is defined as a template meant to specify the names and types of variables that exist in the object. Being the default method of the class, it creates a new instance of the class. The main part to note is that it is the feature of the class (TypeScript or JavaScript ES2015/ES6) and not a concept of Angular. Below mentioned are its different types.

Default Constructor

A constructor is known as the default constructor if it does not take any parameter. Java Compiler inserts the default constructor in the code of developers when they do not supply a constructor for the instantiable class. Its behavior depends on the language. Default constructors can either initialize class members to zero or other same values.

Parameterized Constructor

When the developer takes at least one parameter, it is regarded as a parameterized constructor. It can be used to assign value to the private properties of the class. Interestingly, parameterized constructors automatically call when the programmer creates an object of a specific class.

Copy Constructors

Copy Constructor comprises one formal parameter – the type of the class. It is supported by both C++ and Java. The main use of this type of constructor is to create copies of existing objects of the class. Withal, the overall execution is influenced by the action of the compiler.

Conversion Constructors

Compilers find it easy to create belonging of one class based on the object to a distinguished class with conversion constructors. They convert arguments or operands into a precise type, either implicitly or explicitly.

Move Constructors

Move constructors are indispensable parts of C++ that are harnessed to transfer temporary objects into existing objects. They move resources to the heap and prevent unnecessary copying of data in the memory.

Constructors in Angular

Constructor in Angular is put into use to inject dependencies into the component class. It creates a new instance of the class when the compiler calls ‘new MyClass ()’. While calling ‘new MyClass()’, it is vital that the exact match of the parameter passes the Angular component constructor of the class.

For example, in the new My Class (arg1, arg2, argN), arg1, arg2, and arg3 need to be of the same type as in the constructor of the class.

Angular constructor, in simple words, is meant to write things up in the best form through Dependency Injection. For the people new to Angular, dependency refers to the Angular service or object that class entails to execute the functions. And, dependency injection is a method in which dependencies are requested by class from the external resources.

In the Angular constructor, a constructor argument with dependency type injects the dependencies. It is a must to keep the Angular component constructor simple throughout. The reason being, the simple logic in the Angular constructor, helps in the easy operation of unit testing.

What is a ngOnInit()

Before delving into the concept of angular constructor vs ngOnInit, it is foremost to have a detailed idea about what ngOnInit is. It is basically a lifecycle hook that Angular manages itself. It is called when there is a need to initialize the component after Angular displays the data binding and sets their input properties. Lifecycle Hooks – Lifecycle hooks are referred to as methods on an object or component. They help us know what is happening with components. OnInit is one of the typical lifecycle hooks that are a ship with Angular which determines that the component has been developed.

What is ngOnInit() in Angular?

To use ngOnInit in Angular, it is required to import into the component class in this way – import {Component, OnInit} from ‘@angular/core’. Though implementing ngOnInit for every component is not essential, it is a good practice that further heads towards the smooth functioning of the platform. Angular ngOnInit is created by Angular itself. Angular also renders and checks the changes in its data bounded properties. It is interesting to note that Angular destroys the component before removing it from DOM. ngOnInit in Angular can be hooked to components and directives. Defining the ngOnInit Angular in the class helps Angular runtime to know that is the right time to call the method. The major benefit of this approach is that it adds specific initialization logic near the class lifecycle. Here is a method to implement ngOnInit in Angular.

Step 1: Add OnInit after the implements keywords into a component or directive. Here OnInit will be imported from Angular core and create a contract that implements OnInit.

Step 2: After the addition of OnInit followed by implements, TypeScript will underline the class declaration in red color. This is the indication that ngOnInit was not found. In such a case, creating your own ngOnInit method will help. That’s where the need for explaining the component before and after enters into the play.

Understand difference between constructor & ngOnInit()

Now that the meaning of both Constructor and ngOnInit is clear, it will be easy to evaluate the difference between constructor and ngOnInit. Starting with the basics, the main role of ngOnInit is to provide a signal that Angular has done initializing the component and that users can roll on further. The constructor, on the other hand, is significantly used to initialize the class members but it is unable to perform the whole work. It is only beneficial in the case of dependency injection and initialization of the class field. That being said, the compiler should actually avoid writing the work on Constructor. ngOnInit is a better place to write work code that is required at the time of class instantiation.

What Should Go into Constructor vs NgOnlnit?

Other than their usage, are you wondering what should go into constructor vs ngOnInit? The essential difference between the constructor and ngOnInit can be learned by taking into consideration the following attributes.

JS/TS Language

ngOnInit Angular is just a method in the class. It is directly associated with Angular and is no different from any other method in the class. It is upto the compiler if he wants to implement the method into the class or not. Constructor, on the other hand, is required to be implemented, no matter what. Compiler especially calls it during the creation of a class instance because it can easily transpile JavaScript constructor functions. Thus, in the contrast between typescript constructor vs ngOnInit, the constructor is considered as regardless, no matter if one implements it in the class or not.

Component Initialization Process

Taking in the perspective of the component initialization process, there is a massive difference between the ngOnInit vs constructor. To grasp the comparison, it is important to know that Angular bootstrap comprises two significant steps, that is, the construction of component tree and running change detection. Angular constructor is called when the developer has to construct the component tree. On the flip side, Angular ngOnInit can be a support system in the following change detection phase, when called. Thus it would not be wrong to say that both constructor and ngOnInit help in bootstrapping the application.

Check out the table below to conclude the notion of angular constructor vs ngOnInit.

ngOnInit Angular
It is a lifecycle hook method in Angular It is not directly associated with Angular and is actually a TypeScript feature
It is called when the component is initialized It is called at the time of creating the class’ object
It is a place to write the code that needs to be executed as soon as class is instantiated It initializes the class members
It is used to perform actually business logic It is used in the case of dependency injections
In ngOnInit Angular, everything is often ready at the time of invocation In Angular Constructor, every component is not initialized at the time of invocation

Constructor vs ngOnInit Difference example

The idea of ngOnInit vs constructor can be better understood with the help of an angular constructor example. Though there are several instances to conclude the details regarding typescript constructor vs ngOnInit, the best example would be using the Mat-checkbox. Mat-Checkbox is the component of Angular Material Checkbox. It can either be checked, unchecked, or disabled. Suppose we have two material checkboxes, that is parent component and a child component. Here if we use an @Input decorator for passing value from the parent component to the child component, the constructor will let the @Input property initialize before the component view is set up.

Parent Component

Parent Component

Child Component

Child Component

ngOnInit (), on the other hand, is invoked after the component is initialized. This makes the value of the child component available in the ngOnInit() method. This proves that the ngOnInIt lifecycle hook only initializes the component after Angular displays the data bounded properties. Only after calling once, the method helps us identify that the bindings are readily available. Simply put, out of typescript constructor vs ngOnInit, the latter is a better place to perform work code.

When to use constructor & when to use ngOnInit in Angular

Both ngOnInit Angular and Constructor in Angular feature the concept of object-oriented programming. Taking in account the comparison between angular class constructor vs ngOnInit, the usage of both the lifecycle components can be determined.

Usage Of Constructor In Angular

Angular Constructor is mainly used to inject dependencies in the various artifacts such as services and components. By specifying a constructor parameter with dependency type, programmers can tell Angular to inject dependencies in the component’s constructor. One can also pass the optional dependencies by telling Angular that dependency is optional. This can be done by annotating the parameter with @Optional(). In case a programmer needs to inject additional parameters to Angular service, the @Inject decorator helps to pass the parameters to the Angular service. Whatever be the intention behind injection dependencies, the essential tip is to keep the constructor simple throughout. This is the way to make unit testing simple.

Usage Of ngOnInit in Angular

ngOnInit Angular is simply used to ensure that the initialization code runs. Angular calls ngOnInit after completing the component. This guarantees that the component has been created. In case a programmer requires additional initialization tasks, it is important to define the ngOnInIt () method to handle. The best practice to call ngOnInit again is to implement ‘logic’ in another method and call that method from ngOnInit (). Even the same method can be called again but from another function.

Conclusion

Possessing the knowledge of object-oriented programming can help an individual learn the detailed concept of angular constructor vs OnInit. But as they serve almost similar purposes, the same also confuses even the experienced developer sometimes. Now that the mystery regarding the ngOnInit vs constructor angular is resolved, it makes sense to inject dependencies into the constructor and use ngOnInit when Angular completes creating the component. While the former is helpful in initializing the class members, the latter in the race of angular constructor vs ngOnInit helps better in writing actual work code.

Are you still in a dilemma regarding the concept of angular class constructor vs ngOnInit? There is no time better than now to contact us. Being your state-of-the-art software solution, we can help you have practical ideas if you rely on Angular for developing robust applications.

Talk to us
Let’s talk about your project!
We will contact you as soon as possible