Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 74 ยท Components in Depth

Lifecycle Hooks and afterNextRender

Learn the Angular component lifecycle - ngOnInit, ngOnChanges, ngOnDestroy, afterNextRender, afterEveryRender and DestroyRef - with a runnable simulator.

Every Angular component has a life: Angular creates it, gives it its inputs, renders it, checks it again and again as data changes, and finally destroys it. Lifecycle hooks are methods you can add to a class to run code at specific moments of that life, such as "after the first inputs arrived" or "just before this component disappears".

The hook list is long, but day-to-day Angular uses only a handful. Modern Angular has also added two newer tools that replace several old hooks: afterNextRender / afterEveryRender for code that touches the DOM, and DestroyRef for cleanup that does not need a class method at all. This lesson shows when each one runs and which to reach for.

Real Angular vs stand-in. The typescript blocks below that import from @angular/core are real Angular and read-only here, since the site cannot run the framework. The runnable examples are simulators written in plain TypeScript that follow the same ordering rules, so you can watch the sequence without a compiler or a browser.

The hooks in order

A component that implements the hooks logs them in this order during its first check (constructors and field initializers run first, when Angular creates the object):

Order Hook Runs Typical use
1 constructor once, at creation inject() services, field setup. Inputs are not set yet
2 ngOnChanges before ngOnInit, then on every input change react to input values (decorator inputs)
3 ngOnInit once, after the first ngOnChanges start work that needs the inputs
4 ngDoCheck every change detection run custom change checks (rare)
5 ngAfterContentInit once, after projected content is ready work with projected content
6 ngAfterContentChecked every run, after content is checked rare
7 ngAfterViewInit once, after the component's own view and its children are ready work with child components and view queries
8 ngAfterViewChecked every run, after the view is checked rare
9 ngOnDestroy once, before removal cleanup

ngOnChanges only runs when the component has at least one bound input that changed. A component with no inputs never receives it.

For a parent that contains a child, the order interleaves: the parent's init and content hooks run first, then the child goes through its whole sequence, and the parent's ngAfterViewInit comes last, because a parent's view is only finished when its children's views are.

sequenceDiagram
  participant P as Parent
  participant C as Child
  P->>P: ngOnInit, ngDoCheck
  P->>P: ngAfterContentInit
  P->>C: set inputs
  C->>C: ngOnChanges, ngOnInit, ngDoCheck
  C->>C: ngAfterContentInit
  C->>C: ngAfterViewInit
  P->>P: ngAfterViewInit

On the first check the child finishes its view before the parent's ngAfterViewInit runs.

ngOnChanges and ngOnInit

Here is a real component using the two most common hooks. It reacts when its input changes and starts something once:

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

@Component({
  selector: 'app-greeting',
  template: `<p>Hello, {{ name }}</p>`,
})
export class GreetingComponent implements OnChanges, OnInit {
  @Input() name = '';

  ngOnChanges(changes: SimpleChanges): void {
    const change = changes['name'];
    if (change) {
      console.log(`name: ${change.previousValue} -> ${change.currentValue}`, change.firstChange);
    }
  }

  ngOnInit(): void {
    console.log('ready, first name is', this.name);
  }
}

SimpleChanges maps each changed input to a SimpleChange with previousValue, currentValue and firstChange. It is the way to see what changed. That is also why ngOnInit is the right place for startup work: by then the first input values are in place, while in the constructor they are not.

With signal-based inputs (input(), covered in Inputs and Outputs) you rarely need ngOnChanges. Derive values with computed() and react with effect(); the signals lessons show how.

Simulating the lifecycle

The simulator below models a parent with one child. It does not use Angular; it applies the ordering rules from the table to a tree of plain objects so you can see the sequence for the first check, for a later check after an input changes, and for removing the child.

TypeScript Stand-in: a lifecycle simulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the first check from top to bottom and you can see the pattern. The parent starts, the child does its complete sequence, and only then does the parent finish with ngAfterViewInit. In later checks the "init" hooks never appear again, ngOnChanges shows up only when an input value is different, and the ngDoCheck / ...Checked hooks run every time. That last fact is why you should keep those hooks cheap, and why most code never needs them.

Cleaning up: ngOnDestroy and DestroyRef

Anything you start must be stopped: timers, event listeners on window, subscriptions, third-party widgets. The classic place is ngOnDestroy:

TypeScript
export class ClockComponent implements OnInit, OnDestroy {
  private timerId?: ReturnType<typeof setInterval>;

  ngOnInit(): void {
    this.timerId = setInterval(() => this.tick(), 1000);
  }

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

DestroyRef is the modern alternative. You inject it and register a callback right where you create the resource, so setup and cleanup sit side by side:

TypeScript
import { Component, DestroyRef, inject } from '@angular/core';

@Component({ selector: 'app-clock', template: `{{ now }}` })
export class ClockComponent {
  now = new Date().toLocaleTimeString();

  constructor() {
    const destroyRef = inject(DestroyRef);
    const id = setInterval(() => (this.now = new Date().toLocaleTimeString()), 1000);
    destroyRef.onDestroy(() => clearInterval(id));
  }
}

onDestroy returns a function that unregisters the callback. DestroyRef also works in services, directives and plain functions that run in an injection context, which makes it easy to write reusable helpers that clean up after themselves. Effects created with effect() stop automatically with their owner, and an effect can also receive an onCleanup callback for work to undo before each re-run.

Touching the DOM: afterNextRender and afterEveryRender

Some code needs the real, finished DOM: measuring an element, focusing an input, starting a chart library that wants a container. Doing that in ngOnInit is too early, and in ngAfterViewInit it is awkward on the server, where there is no browser.

afterNextRender runs a callback once, after Angular has finished the next round of rendering, and only in the browser. afterEveryRender runs after every render until you destroy it:

TypeScript
import { Component, ElementRef, afterNextRender, afterEveryRender, viewChild } from '@angular/core';

@Component({
  selector: 'app-chart',
  template: `<div #host class="chart"></div>`,
})
export class ChartComponent {
  private host = viewChild.required<ElementRef<HTMLElement>>('host');

  constructor() {
    afterNextRender(() => {
      const width = this.host().nativeElement.clientWidth;
      console.log('first render finished, width is', width);
    });

    afterEveryRender(() => {
      console.log('a render pass completed');
    });
  }
}

Three rules to remember:

  • Call them in an injection context, usually the constructor or a field initializer. Elsewhere, pass an injector option.
  • They never run during server-side rendering, so browser-only APIs (window, document, localStorage) are safe inside them.
  • Both accept either a plain function or an object of phases (earlyRead, write, mixedReadWrite, read) that run in that order. Putting DOM writes in write and reads in read avoids forcing the browser to recalculate layout repeatedly. Prefer separate write and read phases over mixedReadWrite, and keep afterEveryRender work small because it runs after every pass.

The next stand-in models a scheduler that works this way, together with a DestroyRef. It shows that "next" callbacks run once, "every" callbacks run on each pass, destroying the owner stops them, and nothing runs when there is no browser.

TypeScript Stand-in: render callbacks and DestroyRef

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Pass 1 prints both of A's render callbacks. In pass 2 only the "every" callback runs. In pass 3, B's "next" callback runs once while both "every" callbacks run. After a.destroy() component A is silent and its timer is stopped, which is exactly the behavior you want from a real component. In the server run, the render callbacks are skipped entirely. Real Angular's scheduling is more detailed (phases, coalescing renders), but the contract is the same.

Choosing the right hook

  • Need an input value at startup? ngOnInit.
  • Need to react when an input changes? With signal inputs, computed/effect; with decorator inputs, ngOnChanges.
  • Need to clean up? DestroyRef.onDestroy next to the setup, or ngOnDestroy if you prefer a class method.
  • Need the DOM, a measurement or a browser-only library? afterNextRender (once) or afterEveryRender (each pass).
  • Need child components or view queries ready? ngAfterViewInit, or read the signal queries inside afterNextRender or effect.
  • Avoid heavy work in ngDoCheck and the ...Checked hooks. They run on every check.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A parent contains one child component. During the first check, which of these runs last?

    A parent's view is complete only after its children's views are, so the parent's ngAfterViewInit comes after the child's whole sequence.
  2. 2. Why should you not read an input's value in the constructor of a component using decorator inputs?

    Angular creates the object first and sets inputs afterward. Use ngOnInit (or signals) to work with the first values.
  3. 3. Where is it safe to touch window or measure an element, even when the app is server-side rendered?

    afterNextRender and afterEveryRender run only in the browser, after rendering, so browser-only APIs are safe there.
  4. 4. What does destroyRef.onDestroy(cb) return?

    The returned function removes the callback again, in case you want to cancel the cleanup.
  5. 5. Which hook runs on every change detection pass, so it should stay cheap?

    ngDoCheck and the ...Checked hooks run on every pass. The other three run once.

Summary

  • The usual sequence is constructor, ngOnChanges, ngOnInit, ngDoCheck, the content hooks, the view hooks, and finally ngOnDestroy. The "init" hooks run once; the "check" hooks run on every pass.
  • A parent's ngAfterViewInit runs after its children have finished their views.
  • ngOnChanges receives SimpleChanges and only fires for bound inputs; signal inputs make it mostly unnecessary.
  • DestroyRef.onDestroy registers cleanup next to the setup and works in components, directives and services.
  • afterNextRender and afterEveryRender run browser-only, after rendering, in an injection context, and support phases so DOM writes and reads stay separate.

Next: Template Refs, View Queries and Host Bindings