TExcelTAD
Home › Angular › Lifecycle Hooks

Lifecycle Hooks

Every component goes through a life: Angular creates it, sets its inputs, renders its template, checks it for changes many times, and finally destroys it. Lifecycle hooks are methods you can implement to run code at specific moments in that life.

The hooks in order

Hook Called Typical use
constructor When the class is instantiated inject() dependencies, create signals/effects
ngOnChanges(changes) Before init and whenever an input value changes React to input changes (rarely needed with signal inputs)
ngOnInit() Once, after the first inputs are set Start loading data that depends on inputs
ngDoCheck() On every change detection run Custom change detection (rare)
ngAfterContentInit() Once, after projected content is ready Read contentChild() results
ngAfterViewInit() Once, after the component's view is rendered Read viewChild() results
ngOnDestroy() Just before the component is removed Clean up timers, subscriptions, listeners

Each hook has a matching interface (OnInit, OnDestroy, …). Implementing it is optional but lets TypeScript check the method name for typos.

Seeing the order

angular · try it yourself
import { Component, OnDestroy, OnInit, AfterViewInit, input, signal } from '@angular/core';

@Component({
  selector: 'app-clock',
  template: `<p>{{ label() }}: {{ seconds() }}s</p>`,
})
export class Clock implements OnInit, AfterViewInit, OnDestroy {
  label = input('Elapsed');
  seconds = signal(0);
  private timerId?: ReturnType<typeof setInterval>;

  constructor() { console.log('constructor — label:', this.label()); }

  ngOnInit() {
    console.log('ngOnInit — label:', this.label());
    this.timerId = setInterval(() => this.seconds.update((s) => s + 1), 1000);
  }

  ngAfterViewInit() { console.log('ngAfterViewInit — view is rendered'); }

  ngOnDestroy() {
    clearInterval(this.timerId);
    console.log('ngOnDestroy — timer cleared');
  }
}

@Component({
  selector: 'app-root',
  imports: [Clock],
  template: `
    <button (click)="show.set(!show())">Toggle clock</button>
    @if (show()) { <app-clock label="Session" /> }
  `,
})
export class App { show = signal(true); }
constructor — label: Elapsed
ngOnInit — label: Session
ngAfterViewInit — view is rendered
ngOnDestroy — timer cleared

Two lessons from that log:

  1. In the constructor, inputs still have their default value (Elapsed). Code that needs the real input belongs in ngOnInit — or, better, in a computed().
  2. Clicking Toggle clock removes the component (the @if becomes false), so Angular calls ngOnDestroy. Forgetting clearInterval would leave a timer running forever.

A lifecycle simulator

Here is the same sequence as a plain TypeScript simulation of what the framework does when it creates, updates and destroys a component:

ts · try it yourself
interface Hooks {
  ngOnInit?(): void;
  ngAfterViewInit?(): void;
  ngOnDestroy?(): void;
}

class Profile implements Hooks {
  log: string[] = [];
  userId = 0;
  ngOnInit() { this.log.push(`init(user ${this.userId})`); }
  ngAfterViewInit() { this.log.push('view ready'); }
  ngOnDestroy() { this.log.push('destroyed'); }
}

function mount(inputs: { userId: number }): Profile {
  const cmp = new Profile();          // constructor
  cmp.userId = inputs.userId;         // set inputs
  cmp.ngOnInit?.();                   // once, after inputs
  cmp.ngAfterViewInit?.();            // after the template rendered
  return cmp;
}

const cmp = mount({ userId: 42 });
cmp.ngOnDestroy?.();
console.log(cmp.log.join(' -> '));
init(user 42) -> view ready -> destroyed

Modern alternatives

With signals and inject(), many hooks have simpler replacements:

Old pattern Modern alternative
ngOnChanges to recompute something when an input changes computed(() => …this.someInput()…)
ngOnDestroy to unsubscribe inject(DestroyRef).onDestroy(...) or takeUntilDestroyed()
ngAfterViewInit to touch the DOM afterNextRender(() => …) (runs only in the browser)
@ViewChild read in ngAfterViewInit viewChild() signal, readable in computed/effect
angular · try it yourself
import { Component, DestroyRef, inject, signal } from '@angular/core';

@Component({
  selector: 'app-online-status',
  template: `<p>Status: {{ online() ? '🟢 online' : '🔴 offline' }}</p>`,
})
export class OnlineStatus {
  online = signal(navigator.onLine);

  constructor() {
    const update = () => this.online.set(navigator.onLine);
    window.addEventListener('online', update);
    window.addEventListener('offline', update);

    inject(DestroyRef).onDestroy(() => {
      window.removeEventListener('online', update);
      window.removeEventListener('offline', update);
      console.log('listeners removed');
    });
  }
}

Registering the cleanup right next to the setup keeps related code together — no need to store the handler in a field for a separate ngOnDestroy.

Tip: Keep constructors light. Put heavy or input-dependent work in ngOnInit, and DOM work in afterNextRender, so components stay fast to create and safe to render on the server.

Test yourself

Which hook runs once, after the component's inputs have been set for the first time?

  1. constructor
  2. ngOnInit
  3. ngOnDestroy
  4. ngDoCheck

Where should you clear an interval started by a component?

  1. ngOnInit
  2. The constructor
  3. ngOnDestroy or a DestroyRef.onDestroy callback
  4. Nowhere; Angular clears it

What value does a signal input have when read in the constructor?

  1. The value bound by the parent
  2. Its default value (inputs are not set yet)
  3. Always null
  4. It throws a compile error