Angular Series: Key Concepts in a Flash.

ngOnInit vs. constructor: Exploring Initialization Methods in Angular

Angular Series:  Key Concepts in a Flash.

This blog is the first in the Angular Concepts series . We will explore many other concepts such as Dependency Injection, Data Binding, Router, Services, and much more. If you are a beginner, this will aid you in your journey to learn Angular.

Coding for each instance requires a means of detection. Lifecycle hooks answer this need. Modern front-end frameworks package themselves with a variety of lifecycle hooks. Angular is no exception.

ngOnInit and constructor methods in Angular might be confusing to you ? Why should ngOnInit be used, if we already have a constructor?

What is a Constructor?

A constructor is a special method which will be called whenever we create new objects. And it is responsible for setting up the Angular environment. The constructor can be used to inject dependencies, set the default values for properties, and run any other initialization code that is needed.

Here's an example that demonstrates the use of a constructor in an Angular component for injecting dependencies, such as a service using Dependency Injection.

import { Component } from '@angular/core';
import { DataService } from './data.service'; // Importing the DataService
@Component({
      selector: "app-example",
      template: "<h1>{{title}}</h1>"
})
export class ExampleComponent {
      title: string;
      // Constructor method with dependency injection
      constructor(private dataService: DataService) {}
        this.title = "Angular";
      }
}

This constructor initializes the component's properties title and injects the DataService dependency when an instance of the component is created.

  • It’s better to avoid writing actual work in the constructor.
  • The constructor() should only be used to initialize class members but shouldn’t do actual “work”.
  • So, we should use constructor() to setup Dependency Injection, Initialization of class fields etc.

What is ngOnInit() in Angular?

ngOnInit is a lifecycle hook in Angular, allowing you to tap into the lifecycle of directives and components as they are created, updated, and destroyed. It's defined by the OnInit interface, which Angular utilizes to execute initialization logic.

Angular Lifecycle Hooks:

Angular provides a set of lifecycle hooks, each represented by an interface with a single hook method. For example, ngOnChanges is part of the OnChanges interface.

💡
Each interface defines the prototype for a single hook method, whose name is the interface name prefixed with ng .

These hooks are invoked by Angular in a specific order as follows:

  1. ngOnChanges: Invoked after Angular sets data-bound input properties.

  2. ngOnInit: Invoked once, after the first ngOnChanges.

  3. ngDoCheck: Invoked during every change detection run.

  4. ngAfterContentInit: Invoked after Angular projects external content into the component's view.

  5. ngAfterContentChecked: Invoked after Angular checks the content projected into the component.

  6. ngAfterViewInit: Invoked after Angular initializes the component's views and child views.

  7. ngAfterViewChecked: Invoked after Angular checks the component's views and child views.

  8. ngOnDestroy: Invoked just before Angular destroys the component.

ngOnInit() does not take any parameter.
ngOnInit() will execute if you refresh your browser or first initialize a component but not when other events occur.
Like loading data from Database — to show the user in your HTML template view. Such code should be written in ngOnInit().
💡
To use ngOnInit, we import the OnInit interface from @angular/core.

Here is an example :

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service'; // Importing the DataService
@Component({
selector: 'app-example',
template: <p>Data: {{data}}</p> 
})
export class ExampleComponent {
data: any; 
constructor(private dataService: DataService) {}
ngOnInit() { 
// Accessing the injected service to fetch data
this.data = this.dataService.getData(); 
  }
}

Let's summarize!

The constructor, a default method inherent to TypeScript classes, isn't directly tied to Angular. Generally, it's employed for variable initialization or basic setup tasks. Yet, Angular-specific tasks, such as initializing bindings, are better suited for Angular's ngOnInit lifecycle hook. ngOnInit is specifically designed for Angular-centric initialization activities and is called promptly after the constructor, aligning well with Angular's lifecycle flow.

👋 Thanks for reading! For the next blog post, we'll be diving into Dependency Injection (DI) in Angular. Stay tuned as we explore this fundamental concept in Angular development.