What are Angular Lifecycle Hooks?

Angular components and directives go through lifecycle phases:

  1. Creation → Angular sets up the component.
  2. Rendering → Angular renders templates & bindings.
  3. Update → Angular detects changes.
  4. Destruction → Angular cleans up component.

Lifecycle hooks are special interface methods you can implement to run code at these stages.


2️⃣ Main Lifecycle Hooks in Angular

Hook Interface Called When Example Use Case
ngOnChanges OnChanges Input-bound properties change React to @Input() updates
ngOnInit OnInit Component initialized (after first ngOnChanges) Fetch initial data from API
ngDoCheck DoCheck Every change detection cycle Custom change detection logic
ngAfterContentInit AfterContentInit Projected content initialized (<ng-content>) Access content children after projection
ngAfterContentChecked AfterContentChecked After every check of projected content Detect content changes dynamically
ngAfterViewInit AfterViewInit Component’s view initialized Access @ViewChild elements
ngAfterViewChecked AfterViewChecked After each check of component’s view Run post-render updates
ngOnDestroy OnDestroy Component about to be destroyed Cleanup subscriptions, timers

3️⃣ Basic Example


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

@Component({
  selector: 'app-lifecycle-demo',
  template: `<h3>{{ name }}</h3>`
})
export class LifecycleDemoComponent implements OnInit, OnChanges, OnDestroy {

  @Input() name: string = '';

  constructor() {
    console.log('Constructor called');
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges', changes);
  }

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

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

4️⃣ Hooks in Directives


import { Directive, ElementRef, OnInit, OnDestroy } from '@angular/core';

@Directive({ selector: '[appHighlight]' })
export class HighlightDirective implements OnInit, OnDestroy {

  constructor(private el: ElementRef) {}

  ngOnInit() {
    this.el.nativeElement.style.backgroundColor = 'yellow';
  }

  ngOnDestroy() {
    this.el.nativeElement.style.backgroundColor = '';
  }
}

5️⃣ Practical Enterprise Use Cases

  1. ngOnInit
    • Call API once when component loads.
    • Initialize forms (FormGroup).
  2. ngOnChanges
    • Update component when @Input() changes.
    • React to parent data dynamically.
  3. ngAfterViewInit
    • Access @ViewChild table or chart and apply dynamic logic.
  4. ngOnDestroy
    • Unsubscribe from observables (takeUntil, Subscription.unsubscribe()).
    • Remove timers or DOM event listeners.
  5. ngDoCheck
    • Run custom change detection for non-bound properties.

6️⃣ Quick Tips

  • Use ngOnInit instead of constructor for most initialization.
  • Always unsubscribe in ngOnDestroy to avoid memory leaks (very important for enterprise apps).

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features