WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Angular · Basic · question 17 of 100

What is the purpose of the ngOnInit lifecycle hook in Angular?

📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

The ‘ngOnInit‘ lifecycle hook is a method provided by the Angular framework that gets called automatically after a component is created and its properties are initialized. It is primarily used to perform any additional initialization tasks that couldn’t be performed during the construction or property initialization phase.

The purpose of ‘ngOnInit‘ is to separate the initial setup and configuration of a component from the constructor. The constructor is typically used for dependency injection and basic initialization, while the real component’s behavior and data manipulation should take place inside ‘ngOnInit‘.

The main reason behind this separation is that Angular bindings are not available during the constructor execution, whereas, ngOnInit has access to bindings, inputs, and other dependencies, which makes it a safer place to perform additional setup tasks.

For example, when you are fetching data from a service or a remote API, you should use the ‘ngOnInit‘ method instead of the constructor. Here’s an example that demonstrates the usage of the ‘ngOnInit‘ lifecycle hook:

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

@Component({
  selector: 'app-root',
  template: `
    <div *ngFor="let item of data">
      {{item.name}}
    </div>
  `,
})
export class AppComponent implements OnInit {
  data: any[];

  constructor(private dataService: DataService) {
    // The constructor is used for dependency injection and basic initialization.
  }

  ngOnInit(): void {
    // Fetch the data from the service inside ngOnInit.
    this.dataService.getData().subscribe((response) => {
      this.data = response;
    });
  }
}

In this example, we have a ‘DataService‘ that fetches data from a remote API. The service is injected into the ‘AppComponent‘ constructor. The component fetches the data and assigns it to the ‘data‘ property in the ‘ngOnInit‘ method.

In conclusion, ‘ngOnInit‘ is a lifecycle hook used to perform additional setup required for a component after it is created and ready to interact with other Angular components, inputs, and services.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Angular interview — then scores it.
📞 Practice Angular — free 15 min
📕 Buy this interview preparation book: 100 Angular questions & answers — PDF + EPUB for $5

All 100 Angular questions · All topics