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!

Learn More About Angular πŸš€

What is Angular vs AngularJS πŸ‘‰ Explained
Key Features of Angular πŸ‘‰ Explained
Angular Architecture πŸ‘‰ Explained
Components in Angular πŸ‘‰ Explained
Modules in Angular πŸ‘‰ Explained
Templates in Angular πŸ‘‰ Explained
Directives in Angular πŸ‘‰ Explained
Structural vs Attribute Directives πŸ‘‰ Explained
Services in Angular πŸ‘‰ Explained
Dependency Injection in Angular πŸ‘‰ Explained
Data Binding in Angular πŸ‘‰ Explained
Interpolation πŸ‘‰ Explained
Property Binding πŸ‘‰ Explained
Event Binding πŸ‘‰ Explained
Two-way Data Binding πŸ‘‰ Explained
ngModel Usage πŸ‘‰ Explained
Lifecycle Hooks πŸ‘‰ Explained
ngOnInit Hook πŸ‘‰ Explained
ngOnDestroy Hook πŸ‘‰ Explained
Pipes in Angular πŸ‘‰ Explained
Pure vs Impure Pipes πŸ‘‰ Explained
Create Custom Pipe πŸ‘‰ Explained
Angular Forms πŸ‘‰ Explained
Template-driven vs Reactive Forms πŸ‘‰ Explained
Form Controls πŸ‘‰ Explained
Form Validation πŸ‘‰ Explained
Validation Error Messages πŸ‘‰ Explained
FormGroup vs FormControl πŸ‘‰ Explained
Enable/Disable Form Fields πŸ‘‰ Explained
Reset Form πŸ‘‰ Explained
Routing in Angular πŸ‘‰ Explained
RouterModule πŸ‘‰ Explained
Configure Routes πŸ‘‰ Explained
Route Guards πŸ‘‰ Explained
CanActivate vs CanDeactivate πŸ‘‰ Explained
Lazy Loading πŸ‘‰ Explained
Preloading in Routing πŸ‘‰ Explained
Wildcard Routes πŸ‘‰ Explained
Route Parameters πŸ‘‰ Explained
Query Parameters πŸ‘‰ Explained
Programmatic Navigation πŸ‘‰ Explained
routerLink & routerLinkActive πŸ‘‰ Explained
Resolvers in Routing πŸ‘‰ Explained
Observables in Angular πŸ‘‰ Explained
RxJS in Angular πŸ‘‰ Explained
Observable vs Promise πŸ‘‰ Explained
Share:

Tags:


Feedback Modal Popup