Loading...

ngOnInit in Angular

ngOnInit is a lifecycle hook in Angular that gets executed after Angular has initialized all data-bound properties of a component or directive. It's a key place to perform initialization logic.

Understanding ngOnInit

When an Angular component is created, it goes through a series of lifecycle phases. ngOnInit is the phase that runs after Angular has finished setting up the component's input properties. This makes it ideal for tasks that depend on these inputs.

Why Use ngOnInit?

ngOnInit is commonly used for:

  • Fetching initial data from a service.
  • Setting up event listeners or subscriptions.
  • Initializing component properties based on input values.
  • Performing any setup that requires the component's inputs to be ready.

Implementing ngOnInit

To use ngOnInit, you need to import the OnInit interface from @angular/core and implement the ngOnInit() method in your component.

Example 1: Fetching Data from a Service

This example demonstrates fetching data from a service when the component initializes.


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

    @Component({
      selector: 'app-data-display',
      template: '<ul><li *ngFor="let item of items">{{ item }}</li> </ul>'
    })
    export class DataDisplayComponent implements OnInit {
      items: string[];

      constructor(private dataService: DataService) { }

      ngOnInit() {
        this.items = this.dataService.fetchData();
      }
    }
    

Explanation:

  • implements OnInit: Indicates that the component implements the OnInit interface.
  • ngOnInit(): Called after Angular initializes the component's inputs. We use it to fetch data from the DataService.

Example 2: Initializing Properties Based on Inputs

This example initializes a property based on an input value.


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

    @Component({
      selector: 'app-greeting',
      template: '<p>{{ greetingMessage }}</p>'
    })
    export class GreetingComponent implements OnInit {
      @Input() name: string;
      greetingMessage: string;

      ngOnInit() {
        this.greetingMessage = `Hello, ${this.name}!`;
      }
    }
    

Explanation:

  • @Input() name: string: Defines an input property name.
  • ngOnInit(): Called after Angular initializes the name input. We use it to create a greeting message based on the input value.

Key Points

  • ngOnInit is called after Angular initializes data-bound input properties.
  • It's used for initialization logic that depends on these inputs.
  • Always unsubscribe from observables in ngOnDestroy to prevent memory leaks.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!