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!