askvity

What is ngOnInit in Angular?

Published in Angular Lifecycle Hooks 4 mins read

ngOnInit is a crucial lifecycle hook in Angular that allows you to perform initialization tasks for your component after it has been constructed and its inputs are ready.

Angular components go through various stages, or "lifecycle hooks," from creation to destruction. ngOnInit is one of these important hooks, specifically designed for initialization logic.

Understanding the Angular Component Lifecycle

Angular manages a component's journey through its life cycle. This journey includes:

  • Creating the component
  • Rendering its template
  • Creating and rendering its children
  • Checking when data-bound properties change
  • Destroying the component before removing it from the DOM

Lifecycle hooks are methods you can implement to tap into these key moments.

When ngOnInit is Called

According to the reference, ngOnInit is invoked at a specific point in this lifecycle:

  • It is called after the constructor is called.
  • It is called after the component's inputs have been initialized.

This timing is critical. The constructor is primarily used for dependency injection. ngOnInit, however, is the first place where you can reliably access your component's input properties (@Input()) because Angular ensures they are set before ngOnInit runs.

Purpose and Common Uses

The reference states that ngOnInit is used to perform any additional initialization that is required for the component.

This means ngOnInit is the ideal place for setup logic that depends on inputs or requires interacting with services.

Common tasks performed in ngOnInit include:

  • Fetching data from a service: This is often done when the data needed for the component depends on an input property (e.g., fetching user details based on a user ID passed as an input).
  • Setting up subscriptions: Subscribing to Observables (like those from services or route parameters) is frequently done here.
  • Performing complex calculations: Any setup calculations that rely on initialized inputs.
  • Initializing properties: Setting up internal component properties that require logic beyond simple assignment.

As the reference mentions, ngOnInit is commonly used to call services or to set up subscriptions.

ngOnInit vs. Constructor

While the constructor is called first, ngOnInit is generally preferred for most initialization logic, especially anything involving Angular-specific features like inputs or services that depend on the component's inputs.

Think of it this way:

Feature Constructor ngOnInit
Purpose Dependency Injection Component initialization logic (especially dependent on inputs/services)
Called First After constructor and inputs are initialized
Input Access Inputs are not guaranteed Inputs are guaranteed to be set
Common Use Injecting services, basic setup Data fetching, subscriptions, initialization using inputs

Implementing ngOnInit

To use ngOnInit, your component class must implement the OnInit interface from @angular/core and define the ngOnInit method.

import { Component, OnInit, Input } from '@angular/core';
import { DataService } from './data.service'; // Example service

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

  @Input() itemId: number;
  itemDetails: any;

  constructor(private dataService: DataService) {
    // Constructor: Good for injecting services
    console.log('Constructor called. Input itemId:', this.itemId); // itemId might be undefined here
  }

  ngOnInit(): void {
    // ngOnInit: Inputs are ready!
    console.log('ngOnInit called. Input itemId:', this.itemId); // itemId is available here

    // Common use case: Fetch data based on input
    if (this.itemId) {
      this.dataService.getItemDetails(this.itemId)
        .subscribe(data => {
          this.itemDetails = data;
          console.log('Data fetched:', this.itemDetails);
        });
    }
  }

  // ... other component methods
}

In this example, fetching itemDetails is done in ngOnInit because it relies on the itemId input property being available.

In summary, ngOnInit provides a reliable moment in the component's life to execute necessary setup code after construction and input binding are complete, making it a cornerstone for component initialization in Angular applications.

Related Articles