CPCODELAB
Angular

Lifecycle Hooks

9 min read

Component Lifecycle

Every Angular component goes through a lifecycle: creation, change detection cycles, and eventual destruction. Angular provides lifecycle hook interfaces that let you tap into these moments to run initialization code, react to input changes, or clean up subscriptions.

  1. ngOnChanges — called when @Input() properties change (before ngOnInit)
  2. ngOnInit — called once after the first ngOnChanges; ideal for data fetching
  3. ngDoCheck — called on every change detection run (use sparingly)
  4. ngAfterContentInit — called after <ng-content> is projected
  5. ngAfterViewInit — called after the component's view and child views are initialized
  6. ngOnDestroy — called just before Angular destroys the component; clean up here
ts
import {
  Component, OnInit, OnDestroy, OnChanges,
  Input, SimpleChanges, inject
} from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-lifecycle-demo',
  standalone: true,
  template: `<p>{{ title }}</p>`
})
export class LifecycleDemoComponent implements OnInit, OnDestroy, OnChanges {
  @Input() userId = 0;
  title = '';
  private sub?: Subscription;
  private dataService = inject(DataService);

  ngOnChanges(changes: SimpleChanges) {
    if (changes['userId']) {
      console.log('userId changed to', this.userId);
    }
  }

  ngOnInit() {
    this.sub = this.dataService.getTitle().subscribe(t => {
      this.title = t;
    });
  }

  ngOnDestroy() {
    // Critical: prevent memory leaks
    this.sub?.unsubscribe();
  }
}

Always unsubscribe from Observables in ngOnDestroy, or use Angular's takeUntilDestroyed() operator, to prevent memory leaks when components are removed from the DOM.

Ready to test yourself?
Practice Angular— quiz & coding exercises