Back to all posts

ngOnInit in Angular


ngOnitit is crucial lifecycle hook that allows you to perform initialization tasks in your components.

With OnInit interface enhances type safety and clarity in your code.

What is ngOnInit?

ngOnInit is called once after Angular has initialized all data-bound properties of a component. This hook is ideal for performing tasks such as fetching data from a server, initializing properties, or setting up subscriptions.

Why Implement OnInit?

While you can define ngOnInit without implementing the OnInit interface, doing so provides several benefits:

  • Type Safety: TypeScript checks that your class contains the correct method signature for ngOnInit, preventing errors due to typos.
  • Code Clarity: It signals to other developers that this class adheres to Angular’s lifecycle conventions.
  • Compile-time Errors: If you forget to implement ngOnInit, TypeScript will raise an error, helping you catch mistakes early.

Example of ngOnInit with OnInit Implementation

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<p>{{ message }}</p>',
})
export class ExampleComponent implements OnInit {
  message: string;

  constructor() {
    // Constructor logic can go here
  }

  ngOnInit(): void {
    this.initializeMessage();
  }

  initializeMessage(): void {
    this.message = 'Hello, ngOnInit!';
  }
}