What is ngOnInit Lifecycle Hook in Angular?

πŸ’‘ Concept Name

ngOnInit — A lifecycle hook in Angular that is called once after the component is initialized. It is part of the OnInit interface.

πŸ“œ Quick Intro

ngOnInit() is used to write initialization logic such as API calls, setting up default values, or preparing data before the template is rendered.

🧠 Analogy / Short Story

Imagine you enter a hotel room (component creation). The first thing you do is turn on the lights and unpack (ngOnInit). It's your setup phase before doing anything else.

πŸ”§ Technical Explanation

  • Fires once after the constructor and after the first ngOnChanges
  • Defined by implementing the OnInit interface
  • Commonly used for fetching data or setting up initial logic
  • Angular calls ngOnInit() automatically

🌟 Purpose & Use Case

  • βœ… Fetch data from an API when the component loads
  • βœ… Set initial values for the component state
  • βœ… Perform logic that should run once at initialization

πŸ’» Real Code Example

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

                    @Component({
                        selector: 'app-greeter',
  template: '<h2>Hello, {{name}}</h2>'
                        })
export class GreeterComponent implements OnInit {

  name: string = '';

  ngOnInit() {
    this.name = 'Angular Developer';
    console.log('ngOnInit executed');
  }
}

❓ Interview Q&A

Q1: What does ngOnInit() do?
A: It runs component initialization logic.

Q2: Is ngOnInit called before or after constructor?
A: After constructor.

Q3: Can you make API calls in ngOnInit?
A: Yes, it's a recommended place for that.

Q4: How many times is ngOnInit called?
A: Once per component lifecycle.

Q5: What happens if you don’t implement OnInit?
A: Angular won’t call ngOnInit().

πŸ“ MCQs

Q1. What lifecycle hook is called after component constructor?

  • ngOnDestroy
  • ngOnInit
  • ngAfterViewInit
  • ngOnChanges

Q2. Where is it best to make API calls in Angular?

  • constructor
  • ngOnDestroy
  • ngOnInit
  • ngAfterContentInit

Q3. Which interface is required for ngOnInit?

  • OnChanges
  • DoCheck
  • AfterViewInit
  • OnInit

Q4. How often is ngOnInit executed?

  • Every render
  • Once
  • On input change
  • Never

Q5. What will happen if ngOnInit is declared but OnInit is not implemented?

  • It throws error
  • ngOnInit won't be called
  • It works fine
  • ngOnDestroy is triggered

πŸ’‘ Bonus Insight

Avoid putting logic in the constructor. Use ngOnInit instead because the component inputs are not yet resolved in the constructor.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: