Skip to the workspace
Pebellslearn by building
Template Syntax and Lifecycle  ›  Lesson

The Component Lifecycle

Component Lifecycle 15 minAngular calls lifecycle hooks at fixed moments in a component's life, so setup that needs inputs goes in ngOnInit, work that needs the rendered view waits for the view, and cleanup goes in ngOnDestroy.

angular / The Component Lifecycle

Explore each scene at your own pace.

01 · The rule

The rule

The Component Lifecycle

PlantTimer shows "watered 3 hours ago" and ticks every minute. It needs its plant before it can start, and it must stop ticking when the user leaves the page. Angular tells a component when these moments arrive through lifecycle hooks: methods it calls at fixed points.

The rule

Construct to exist, init to start, destroy to clean up.

The main hooks, in the order Angular calls them:

Hook When Typical use
constructor Class created Inject services; nothing else
ngOnChanges An input changed (also before init) React to new input values
ngOnInit Once, after the first inputs are set Start work that needs inputs
ngAfterViewInit Once, after the template and children render Touch elements found by viewChild
ngOnDestroy Just before removal Stop timers, release resources

There are also ngDoCheck, ngAfterContentInit, ngAfterContentChecked and ngAfterViewChecked for rarer cases.

import { Component, OnDestroy, OnInit, input, signal } from '@angular/core';

@Component({
  selector: 'app-plant-timer',
  template: `<p>Watered {{ minutesAgo() }} minutes ago</p>`,
})
export class PlantTimer implements OnInit, OnDestroy {
  plant = input.required<Plant>();
  minutesAgo = signal(0);
  private timerId = 0;

  ngOnInit() {
    this.tick();
    this.timerId = setInterval(() => this.tick(), 60_000);
  }

  ngOnDestroy() {
    clearInterval(this.timerId);
  }

  private tick() {
    const ms = Date.now() - this.plant().lastWatered.getTime();
    this.minutesAgo.set(Math.floor(ms / 60_000));
  }
}

Implementing the OnInit and OnDestroy interfaces is optional, but it lets TypeScript catch a misspelled hook name.

Signal-era helpers cover the same moments: inject(DestroyRef).onDestroy(...) registers cleanup from anywhere, and afterNextRender(...) runs code once the browser has drawn the component.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.