Angular Component Lifecycle Hooks

Angular Component Lifecycle Hooks

Angular calls lifecycle hook methods at specific moments in a component's life — from creation through destruction.

Lifecycle Sequence

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

@Component({ selector: 'app-demo', standalone: true, template: '...' })
export class DemoComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {

  @Input() userId!: number;

  // Called before ngOnInit, every time an @Input changes
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['userId']) {
      const { previousValue, currentValue } = changes['userId'];
      console.log(`userId changed: ${previousValue} → ${currentValue}`);
      this.loadUser(currentValue);
    }
  }

  // Called once after first ngOnChanges — initialise logic here
  ngOnInit(): void {
    console.log('Component initialised');
  }

  // Called after Angular initialises the component's view
  ngAfterViewInit(): void {
    console.log('View ready — safe to access @ViewChild refs');
  }

  // Called just before Angular destroys the component
  ngOnDestroy(): void {
    console.log('Cleanup — unsubscribe, clear timers');
    this.subscription?.unsubscribe();
  }
}

Most Common Hooks

HookWhenUse For
ngOnInitAfter first renderFetch data, setup
ngOnChangesOn @Input changeReact to prop changes
ngAfterViewInitAfter view rendersAccess DOM, @ViewChild
ngOnDestroyBefore destructionCleanup, unsubscribe