What are Lifecycle Hooks in Angular?

💡 Concept Name

Lifecycle Hooks – Special methods in Angular that allow you to tap into different phases of a component’s life, like initialization, change detection, and destruction.

📘 Quick Intro

Angular lifecycle hooks are callback methods that provide visibility into key moments in a component or directive’s life, such as when it’s created, updated, or destroyed. Common hooks include ngOnInit, ngOnChanges, and ngOnDestroy.

🧠 Analogy / Short Story

Think of a component like a plant. It gets planted (ngOnInit), grows and reacts to sunlight and water changes (ngOnChanges), and eventually gets trimmed or removed (ngOnDestroy). Lifecycle hooks are how Angular nurtures your component from seed to sunset.

🔧 Technical Explanation

  • ngOnInit(): Called once after the component is initialized—perfect for API calls or setup.
  • ngOnChanges(): Called whenever input properties change.
  • ngOnDestroy(): Called before the component is removed—used for cleanup.
  • Other hooks include ngAfterViewInit, ngDoCheck, ngAfterContentInit, etc.

🎯 Purpose & Use Case

  • ✅ Initialize data and make API calls using ngOnInit
  • ✅ Detect and respond to input changes with ngOnChanges
  • ✅ Perform cleanup (e.g., unsubscribe) in ngOnDestroy
  • ✅ Hook into content or view child initialization

💻 Real Code Example

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

@Component({
  selector: 'app-example',
  template: '<p>Hello, {{name}}</p>'
})
export class ExampleComponent implements OnInit, OnChanges, OnDestroy {

  @Input() name: string = '';

  ngOnInit() {
    console.log('Component initialized');
  }

  ngOnChanges() {
    console.log('Input property changed');
  }

  ngOnDestroy() {
    console.log('Component destroyed');
  }
}

❓ Interview Q&A

Q1: What is ngOnInit used for?
A: It is used for component initialization, like fetching data or setting initial values.

Q2: When is ngOnDestroy called?
A: Before a component is removed from the DOM to perform cleanup tasks.

Q3: Which hook detects input property changes?
A: ngOnChanges

Q4: Can a component have multiple lifecycle hooks?
A: Yes, it can implement several lifecycle interfaces.

Q5: What happens if ngOnDestroy is not implemented?
A: Cleanup code like unsubscribing may be missed, leading to memory leaks.

📝 MCQs

Q1. Which lifecycle hook is called after the component's first display?

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterViewInit

Q2. Which lifecycle hook detects changes in @Input properties?

  • ngAfterViewInit
  • ngOnInit
  • ngOnChanges
  • ngOnDestroy

Q3. Which lifecycle method is used to unsubscribe from observables?

  • ngOnInit
  • ngAfterContentChecked
  • ngOnDestroy
  • ngDoCheck

Q4. What interface is implemented to use ngOnInit?

  • OnStart
  • OnInit
  • InitHook
  • StartComponent

Q5. What does ngOnDestroy help prevent?

  • Null exceptions
  • Slow rendering
  • Memory leaks
  • Change detection

Q6. When is ngOnChanges triggered?

  • After initialization
  • Before view loads
  • When an @Input value changes
  • During module load

Q7. Which hook runs only once during the component lifecycle?

  • ngOnChanges
  • ngDoCheck
  • ngAfterViewInit
  • ngOnInit

Q8. What is the purpose of ngAfterViewInit?

  • Runs on input change
  • Resets the state
  • Detect changes after component view is initialized
  • Destroy DOM

Q9. Can ngOnInit and ngOnDestroy exist together?

  • Yes
  • No
  • Only in services
  • Only in modules

Q10. What should be avoided inside ngOnDestroy?

  • Cleanup logic
  • Unsubscribe
  • Heavy async operations
  • Logging

💡 Bonus Insight

Always unsubscribe from observables and detach event listeners in ngOnDestroy to avoid memory leaks. Use tools like takeUntil() with Subject for efficient teardown.

📄 PDF Download

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

💬 Feedback
🚀 Start Learning
Share:

Tags: