Angular Lifecycle Hooks — Your Quick Interview-Ready Notes #1

Let’s dive into Angular Lifecycle Hooks — explained simply with purpose, usage, and quick examples.

🧠 What Are Lifecycle Hooks?

Lifecycle hooks are special methods in Angular that allow you to tap into the key moments of a component’s life, such as creation, changes, and destruction.

📋 List of Common Lifecycle Hooks (with Purpose)

Hook Purpose
ngOnChanges() Called when @Input() properties change (on init + every change).
ngOnInit() Called once after first ngOnChanges. Ideal for initialization logic.
ngDoCheck() Called during every change detection cycle. Use for custom change detection.
ngAfterContentInit() Called once after content projection (<ng-content>) is initialized.
ngAfterContentChecked() Called after every check of projected content.
ngAfterViewInit() Called after component’s view & child views are initialized.
ngAfterViewChecked() Called after every check of component’s view & child views.
ngOnDestroy() Called right before component is destroyed. Use for cleanup (unsubscribe, etc.).

💡 Use-Cases for Interviews

Hook When to Use
ngOnInit() API calls, fetching data, initializing variables
ngOnDestroy() Clear setInterval, unsubscribe() from observables
ngOnChanges() React to changes in @Input() values
ngAfterViewInit() DOM manipulations, working with @ViewChild()
ngDoCheck() Track non-@Input() changes manually

✍️ Mini Code Example

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

@Component({
  selector: 'app-user',
  template: `<p>{{ name }}</p>`
})
export class UserComponent implements OnInit, OnDestroy, OnChanges {
  @Input() name: string = '';

  ngOnChanges() {
    console.log('ngOnChanges - name changed');
  }

  ngOnInit() {
    console.log('ngOnInit - component initialized');
  }

  ngOnDestroy() {
    console.log('ngOnDestroy - component destroyed');
  }
}

✅ Quick Mnemonic (for ordering)

👉 Changes → Init → DoCheck → ContentInit → ContentChecked → ViewInit → ViewChecked → Destroy

CID-CC-VVD


🔁 Common Interview Questions

  1. Which hook runs first in Angular?
    👉 ngOnChanges() if @Input() exists, otherwise ngOnInit()
  2. When to use ngOnDestroy()?
    👉 To clean up Observables, WebSocket connections, or intervals.
  3. Difference between ngOnInit() and constructor?
    👉 constructor sets up class (no DOM yet), ngOnInit() is where DOM + bindings are ready.
  4. Can ngOnChanges() run multiple times?
    👉 Yes, every time an @Input() changes.

Would you like the next topic to be @Input() / @Output(), or shall we go deeper into RxJS (ngAfterViewInit, ViewChild, etc.)?

Let me know — and keep noting these with your pen & paper 📖🖊️!