Blog

Part 10 · viewChild, contentChild and the Component Lifecycle in Angular

Sometimes a component needs the real element, to focus it or measure it. This part covers viewChild, viewChildren, contentChildren, afterNextRender, afterRenderEffect, DestroyRef and the lifecycle hooks in older code.

Most of the time a template does the work for you. You bind a value, and Angular keeps the screen in step. But some jobs need the real element on the page: putting the cursor in a search box, measuring how wide something is, scrolling to an item. And some jobs need to stop when the component goes away, like a timer.

This part covers getting hold of things in your template with viewChild, viewChildren and contentChildren, running code after Angular has drawn the page with afterNextRender and afterRenderEffect, cleaning up with DestroyRef, and the lifecycle hooks such as ngOnInit that you’ll still meet. It builds on signals from Part 3, inputs from Part 5 and ng-content from Part 9. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

Paste this into src/app/app.ts. It asks Angular for the <input> twice: once while the component is being built, and once after the page is drawn.

// src/app/app.ts
import { afterNextRender, Component, ElementRef, viewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<input #search aria-label="Search" />`,
})
export class App {
  private readonly search = viewChild<ElementRef<HTMLInputElement>>('search');

  constructor() {
    console.log('in the constructor:', this.search());
    afterNextRender(() => {
      console.log('after the first render:', this.search()?.nativeElement.tagName);
    });
  }
}

Before you read on, guess. Open the browser’s console (F12). What do the two lines say?

Here’s what it logs:

in the constructor: undefined
after the first render: INPUT

The first line says undefined. When the constructor runs, Angular is still building the component. The template hasn’t been drawn, so there’s no <input> yet. By the time afterNextRender runs, it is there. Most of this part follows from that one fact.

viewChild: a signal that points into your template

#search is a template reference variable from Part 2. It gives an element a name inside the template. viewChild('search') lets the class find that element by the same name.

What you get back is a signal. Like every signal, you read it by calling it: this.search(). Its value is an ElementRef, a small wrapper Angular puts around a DOM element. The real element is its nativeElement property.

The type in angle brackets is a generic, as in Part 3. viewChild<ElementRef<HTMLInputElement>> says “this will hold an ElementRef around an <input>“. Angular can’t check the name 'search' against the template’s types, so you say what you expect. With it, TypeScript knows that nativeElement has focus() and value.

The signal is undefined until the element exists. That’s also true when the element sits inside an @if that is false. Here the template shows what the query has found:

// src/app/app.ts
import { Component, ElementRef, signal, viewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="show.set(!show())">Toggle</button>
    @if (show()) {
      <input #box aria-label="Name" />
    }
    <p>Box: {{ box() ? 'found' : 'none' }}</p>
  `,
})
export class App {
  protected readonly show = signal(false);
  protected readonly box = viewChild<ElementRef<HTMLInputElement>>('box');
}

The page shows:

Toggle
Box: none

Click Toggle, and the input appears. The page now shows:

Toggle
Box: found

The query follows the template. When the @if adds the input, the signal gets it. When the @if removes it, the signal goes back to undefined. Anything that reads the signal, like this template, updates too.

viewChild.required

If the element is always in the template, not inside an @if or @for, use viewChild.required. Its signal has no undefined in its type, so you write this.search().nativeElement without the ?.. It’s still empty before the first render. The difference is that reading it too early is now an error, at build time (NG8118) or at runtime (NG0951), instead of a silent undefined. A worked example below shows that error.

afterNextRender: DOM work once the page is drawn

afterNextRender(fn) runs fn once, after Angular has next drawn the page. The DOM is up to date by then. That’s the place for a job you can’t do with a binding, like focusing an input.

Here’s a search box that puts the cursor in itself when the page opens. To prove it worked, the input’s (focus) event sets a signal that the page shows:

// src/app/app.ts
import { afterNextRender, Component, ElementRef, signal, viewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input #search aria-label="Search" (focus)="focused.set(true)" />
    <p>Focused: {{ focused() }}</p>
  `,
})
export class App {
  private readonly search = viewChild.required<ElementRef<HTMLInputElement>>('search');
  protected readonly focused = signal(false);

  constructor() {
    afterNextRender(() => this.search().nativeElement.focus());
  }
}

Without clicking anything, the page shows:

Focused: true

A few things to notice:

  • afterNextRender is called in the constructor, but its function runs later. That’s why reading this.search() inside it is fine.
  • It runs once. If the page redraws later, it doesn’t run again. (afterEveryRender runs after every render, but you’ll rarely need it.)
  • It never runs during server-side rendering, where there’s no real DOM. That makes it the safe home for browser-only code. Part 29 covers server rendering.

autofocus on the input would also work for a page that loads once. It doesn’t work for an input that appears later, for example inside an @if: the browser only autofocuses once per page. afterNextRender works for both.

viewChild with a component

viewChild can look for a component class instead of a name. Then you get the component’s instance and can call its public methods. Here’s a counter, in its own file, with a public reset():

// src/app/counter.ts
import { Component, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <p>Count: {{ count() }}</p>
    <button (click)="count.update((n) => n + 1)">Add one</button>
  `,
})
export class Counter {
  protected readonly count = signal(0);

  reset() {
    this.count.set(0);
  }
}
// src/app/app.ts
import { Component, ElementRef, viewChild } from '@angular/core';
import { Counter } from './counter';

@Component({
  selector: 'app-root',
  imports: [Counter],
  template: `
    <app-counter />
    <button (click)="resetCounter()">Reset</button>
  `,
})
export class App {
  private readonly counter = viewChild.required(Counter);
  private readonly counterHost = viewChild.required(Counter, { read: ElementRef });

  protected resetCounter() {
    this.counter().reset();
    console.log('reset', this.counterHost().nativeElement.tagName);
  }
}

Click Add one twice, then Reset. The page shows:

Count: 0
Add oneReset

(The two buttons run together as Add oneReset because buttons sit on one line, and the page text joins them.) The console shows:

reset APP-COUNTER

With a class, you don’t need the generic. viewChild.required(Counter) already knows it holds a Counter.

The second query adds { read: ElementRef }. A query finds a place in the template, and read says what you want from that place. For <app-counter /> the default is the component. read: ElementRef asks for its host element, <app-counter>, instead. For a plain element like <input #search>, the default is already the ElementRef.

Reach for this sparingly. Data and events between parent and child go through inputs (Part 5) and outputs (Part 6). A query is for the few jobs that really are commands: reset, play, focus, scroll.

viewChildren: one signal for many

viewChildren is the plural. It returns a signal holding a read-only array of every match, in template order. When @for adds or removes elements, the array follows. Its type is Signal<ReadonlyArray<T>>, so this.fields().length and this.fields().at(-1) work as with any array. at(-1) is plain JavaScript for “the last item”. The first worked example below uses it.

contentChildren: what the parent put inside you

In Part 9, a parent put content between a component’s tags, and <ng-content /> showed it. viewChild can’t see that content, because it isn’t in the component’s own template. The parent’s template wrote it. For projected content you use contentChild (the first match) and contentChildren (all of them).

Here a Tabs component reads the label of every Tab placed inside it, to build a row of tab names:

// src/app/tab.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-tab',
  template: `<p><ng-content /></p>`,
})
export class Tab {
  readonly label = input.required<string>();
}
// src/app/tabs.ts
import { Component, contentChildren } from '@angular/core';
import { Tab } from './tab';

@Component({
  selector: 'app-tabs',
  template: `
    <p>
      @for (tab of tabs(); track tab) {
        [{{ tab.label() }}]
      }
    </p>
    <ng-content />
  `,
})
export class Tabs {
  protected readonly tabs = contentChildren(Tab);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Tab } from './tab';
import { Tabs } from './tabs';

@Component({
  selector: 'app-root',
  imports: [Tabs, Tab],
  template: `
    <app-tabs>
      <app-tab label="Home">Welcome home.</app-tab>
      <app-tab label="Help">Ask us anything.</app-tab>
    </app-tabs>
  `,
})
export class App {}

The page shows:

[Home] [Help]
Welcome home.
Ask us anything.

Tabs never names the tabs itself. Add a third <app-tab> in App, and the row grows. track tab tracks each tab by the instance itself, which is fine here, since each one is a different object.

afterRenderEffect: DOM work every time a signal changes

afterNextRender runs once. Sometimes the DOM work has to follow a signal: redraw a chart when its data changes, keep a list scrolled to the bottom when a message arrives. That’s afterRenderEffect. It’s like effect from Part 8: it runs a function and runs it again whenever a signal it read changes. The difference is when. An effect in a component runs before Angular updates the page. afterRenderEffect runs after.

This example shows the difference. A bar gets its width from a signal, and both kinds of effect measure it:

// src/app/app.ts
import { afterRenderEffect, Component, effect, ElementRef, signal, viewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <span
      #bar
      [style.width.px]="size()"
      style="display: inline-block; height: 10px; background: teal"
    ></span>
    <button (click)="grow()">Grow</button>
  `,
})
export class App {
  protected readonly size = signal(100);
  private readonly bar = viewChild.required<ElementRef<HTMLSpanElement>>('bar');

  constructor() {
    effect(() => console.log('effect', this.size(), this.bar().nativeElement.offsetWidth));
    afterRenderEffect({
      read: () =>
        console.log('afterRenderEffect', this.size(), this.bar().nativeElement.offsetWidth),
    });
  }

  protected grow() {
    this.size.update((n) => n + 50);
  }
}

[style.width.px] is a style binding: it sets the width in pixels from size(). offsetWidth is the browser’s measured width. The { read: ... } object names the phase the function runs in. Measuring the page is a read. More on phases below. When the page loads, the console shows:

effect 100 0
afterRenderEffect 100 100

Click Grow. The console shows:

effect 150 100
afterRenderEffect 150 150

Both times, the effect measured a bar that hadn’t been updated yet. On load it saw width 0, because the style binding hadn’t been applied. After the click it saw 100, the old width. afterRenderEffect measured the bar the user actually sees. Use it when the code reads or changes the DOM, and keep using computed and bindings for everything else.

There are four phases: earlyRead, write, mixedReadWrite and read. After a render, Angular runs all the write functions before all the read functions. Mixing writes and reads forces the browser to work out the layout again after each write, which is slow on a big page. So put code that changes the DOM in write and code that measures it in read. You can also pass a plain function, to afterNextRender or afterRenderEffect. It runs in mixedReadWrite, and Angular’s docs warn that this can be slow when many components do it. A one-off focus(), as in our examples, is fine. For anything that measures or changes layout, name a phase.

DestroyRef: cleaning up when the component goes

A component can start something that keeps running on its own: a setInterval, a listener on window, a connection. When the component is removed, those keep going unless you stop them. DestroyRef lets you register cleanup code. You get it with inject(DestroyRef) and call its onDestroy(fn).

inject() asks Angular for something by its type. Part 13 covers it in depth; for now, read inject(DestroyRef) as “give me this component’s DestroyRef”. Like afterNextRender, it has to be called while the component is being built: in the constructor or a field initializer.

The second worked example below is a clock that stops its timer this way.

The lifecycle hooks you’ll still see

Before signals, a component did this kind of work in lifecycle hooks: methods with special names that Angular calls at fixed moments. They still work, and you’ll meet them in most existing code. Here’s a component that logs each one, shown and hidden by an @if:

// src/app/life.ts
import { afterNextRender, Component, DestroyRef, inject } from '@angular/core';

@Component({
  selector: 'app-life',
  template: `<p>Alive</p>`,
})
export class Life {
  constructor() {
    console.log('constructor');
    afterNextRender(() => console.log('afterNextRender'));
    inject(DestroyRef).onDestroy(() => console.log('DestroyRef.onDestroy'));
  }

  ngOnInit() {
    console.log('ngOnInit');
  }

  ngAfterViewInit() {
    console.log('ngAfterViewInit');
  }

  ngOnDestroy() {
    console.log('ngOnDestroy');
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Life } from './life';

@Component({
  selector: 'app-root',
  imports: [Life],
  template: `
    <button (click)="show.set(!show())">Toggle</button>
    @if (show()) {
      <app-life />
    }
  `,
})
export class App {
  protected readonly show = signal(true);
}

When the page loads, the console shows:

constructor
ngOnInit
ngAfterViewInit
afterNextRender

Click Toggle to remove it. The console shows:

ngOnDestroy
DestroyRef.onDestroy

What each one is for:

  • constructor: the class is being built. Field initializers run here too. Inputs don’t have their values yet, and the template hasn’t been drawn.
  • ngOnInit: runs once, after the inputs have their first values and before Angular first fills in the template’s values. Old code used it for “start up with my inputs”. Today a computed follows the inputs, so you rarely need it.
  • ngAfterViewInit: runs once, after the component’s own template and its children are created, so view queries have their results. Old code did DOM work here. afterNextRender replaces it. The difference is that it waits until the whole app has rendered, not just this component, and it doesn’t run on the server.
  • ngOnDestroy: runs once, just before the component is removed. DestroyRef.onDestroy replaces it, and you can register a cleanup right next to the code that needs it.

There are more hooks (ngOnChanges, ngDoCheck, ngAfterContentInit and the ...Checked ones). You’ll see them in older code; new code rarely needs them.

A component’s life, from creation to destroy

This animation follows a clock component like the one in the second worked example, from the moment an @if creates it to the moment it removes it.

App (parent) @if (show()) Clock component seconds: 0 seconds: 1 no DOM yet Seconds: 0 Seconds: 1 destroyed created rendered updated destroyed what happens constructor and field initializers run inputs get their first values next viewChild() is undefined: no DOM yet the template is drawn into the page viewChild() now holds the element afterNextRender runs, once the timer calls seconds.update() Angular redraws only the changed text an afterRenderEffect that read it runs show() is false: the view is removed ngOnDestroy and DestroyRef.onDestroy run clearInterval: the timer stops seconds 0, no DOM, viewChild() undefined seconds 0, the screen shows Seconds: 0 seconds 1, the screen shows Seconds: 1 the component and its DOM are gone, the timer is cleared Created: Angular builds the class. Nothing is on the page yet First render: the template is drawn and queries get their elements Update: a signal changes and the template is redrawn Destroyed: @if turns false, the cleanup runs, the timer stops

A component is built before its template exists, drawn, redrawn when its signals change, and cleaned up when it is removed.

Here are those steps in words, in case the animation doesn’t play for you:

  1. Created. The @if turns true, and Angular builds a Clock. The constructor and field initializers run. The inputs, if it has any, get their first values right after. Nothing is on the page yet, so viewChild() is undefined.
  2. First render. Angular draws the template, which reads the seconds signal and shows Seconds: 0. Queries now hold their elements, and afterNextRender runs, once.
  3. Update. The timer calls seconds.update(). Angular redraws only the text that changed. An afterRenderEffect that read seconds would run after this render.
  4. Destroyed. show() turns false. Angular removes the clock’s DOM, calls ngOnDestroy and the DestroyRef.onDestroy functions (in the run above, in that order), and the timer is cleared. The component is gone.

Worked example: a list that focuses the new row

A form with a list of rows: names of people coming to a party. Clicking Add row adds an empty field, and the cursor should jump into it, so the user can type straight away. The (focus) handler shows which row is being edited:

// src/app/app.ts
import {
  afterNextRender,
  Component,
  computed,
  ElementRef,
  inject,
  Injector,
  signal,
  viewChildren,
} from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    @for (row of rows(); track row) {
      <input #field [attr.aria-label]="'Row ' + row" (focus)="editing.set(row)" />
    }
    <button (click)="add()">Add row</button>
    <p>{{ count() }} fields, editing row {{ editing() }}</p>
  `,
})
export class App {
  private readonly injector = inject(Injector);
  protected readonly rows = signal([1, 2]);
  protected readonly editing = signal(0);
  private readonly fields = viewChildren<ElementRef<HTMLInputElement>>('field');
  protected readonly count = computed(() => this.fields().length);

  protected add() {
    this.rows.update((list) => [...list, list.length + 1]);
    afterNextRender(() => this.fields().at(-1)?.nativeElement.focus(), {
      injector: this.injector,
    });
  }
}

The page shows:

Add row
2 fields, editing row 0

Click Add row. The page shows:

Add row
3 fields, editing row 3

Walk through the click:

  1. add() puts a third row in rows. The new <input> doesn’t exist yet. Angular draws it after the handler has finished.
  2. So add() doesn’t focus anything itself. It asks afterNextRender to do it once the page is drawn.
  3. After the render, fields() holds three elements. at(-1) is the new one, and it gets the focus. Its (focus) handler sets editing to 3.

count is a computed from the query, so the template shows how many fields the query has found. It went from 2 to 3 without any code of ours.

The injector option is the new part. afterNextRender needs to know which component it belongs to, so it can be cleaned up when that component goes. In a constructor, Angular knows. In a click handler, it doesn’t, so we pass the component’s Injector, which we saved with inject(Injector) while the component was being built. Leave the option out and the click fails:

// src/app/app.ts
import { afterNextRender, Component, ElementRef, signal, viewChildren } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    @for (row of rows(); track row) {
      <input #field [attr.aria-label]="'Row ' + row" />
    }
    <button (click)="add()">Add row</button>
  `,
})
export class App {
  protected readonly rows = signal([1, 2]);
  private readonly fields = viewChildren<ElementRef<HTMLInputElement>>('field');

  protected add() {
    this.rows.update((list) => [...list, list.length + 1]);
    afterNextRender(() => this.fields().at(-1)?.nativeElement.focus());
  }
}

Click Add row. The third field appears, but the cursor stays where it was, and the console has an error:

ERROR RuntimeError: NG0203: afterNextRender() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`. Find more at https://v22.angular.dev/errors/NG0203

An injection context is the time while Angular is building something, when it knows which component the code belongs to. The constructor and field initializers are inside it. A click handler runs long after, outside it. inject() in a handler fails with NG0203 too, so save what you need in a field while the component is being built, as we did with Injector.

Worked example: a clock that stops when it’s hidden

A clock starts a timer when it appears and must stop it when it goes:

// src/app/clock.ts
import { Component, DestroyRef, inject, signal } from '@angular/core';

@Component({
  selector: 'app-clock',
  template: `<p>Seconds: {{ seconds() }}</p>`,
})
export class Clock {
  protected readonly seconds = signal(0);

  constructor() {
    const id = setInterval(() => this.seconds.update((n) => n + 1), 1000);
    console.log('clock started');
    inject(DestroyRef).onDestroy(() => {
      clearInterval(id);
      console.log('clock stopped');
    });
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Clock } from './clock';

@Component({
  selector: 'app-root',
  imports: [Clock],
  template: `
    <button (click)="show.set(!show())">Toggle clock</button>
    @if (show()) {
      <app-clock />
    }
  `,
})
export class App {
  protected readonly show = signal(true);
}

When the page loads, the console shows:

clock started

After about a second and a half, the page shows:

Toggle clock
Seconds: 1

Click Toggle clock. The clock disappears, and the console shows:

clock stopped

Click it again. A new clock appears, starting from zero, and the console shows:

clock started
Toggle clock
Seconds: 0

Each time the @if turns true, Angular builds a new Clock, with a new seconds signal and a new timer. Each time it turns false, the old one is destroyed and its cleanup runs.

The cleanup sits right next to the setInterval it undoes. id is a local variable in the constructor, and the cleanup function can still use it. In older code, the id had to go in a field so that ngOnDestroy, a separate method, could reach it.

Without the cleanup, the hidden clock’s timer would keep running forever, holding on to the destroyed component. Show and hide it ten times, and ten timers tick. Nothing on the page shows it. Exercise 2 makes this kind of leak visible.

Worked example: reading an input too early

A greeting component builds its text from a required input:

// src/app/greeting.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-greeting',
  template: `<p>{{ text }}</p>`,
})
export class Greeting {
  readonly name = input.required<string>();
  protected readonly text = 'Hello, ' + this.name();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Greeting } from './greeting';

@Component({
  selector: 'app-root',
  imports: [Greeting],
  template: `<app-greeting name="Ana" />`,
})
export class App {}

The build stops:

✘ [ERROR] NG8118: `name` is a required `input` and does not have a value in this context. [plugin angular-compiler]
10 │   protected readonly text = 'Hello, ' + this.name();

Read it piece by piece:

  • NG8118 is an Angular compiler error. The compiler checks your class, not just your template.
  • `name` is a required `input` names the input. does not have a value in this context says where you read it is too early.
  • The underlined line is the field initializer. Field initializers run while the class is built, as part of the constructor. Inputs get their values after that. So at this point name has nothing to give, and a required input has no default to fall back on.

The compiler spots a read in a field initializer or the constructor itself. It can’t follow every path. Hide the same read inside a method, and it builds:

// src/app/greeting.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-greeting',
  template: `<p>{{ text }}</p>`,
})
export class Greeting {
  readonly name = input.required<string>();
  protected readonly text = this.makeText();

  private makeText() {
    return 'Hello, ' + this.name();
  }
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Greeting } from './greeting';

@Component({
  selector: 'app-root',
  imports: [Greeting],
  template: `<app-greeting name="Ana" />`,
})
export class App {}

The page stays blank, and the console shows:

ERROR RuntimeError: NG0950: Input "name" is required but no value is available yet. Find more at https://v22.angular.dev/errors/NG0950

It’s the same mistake, caught later. Angular’s runtime check fires when makeText() reads this.name(). The error stops Angular from finishing the page, so nothing shows at all.

An input that isn’t required is worse, because there’s no error. It has a default value, and that’s what a field initializer gets:

// src/app/greeting.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-greeting',
  template: `<p>{{ text }}</p>`,
})
export class Greeting {
  readonly name = input('nobody');
  protected readonly text = 'Hello, ' + this.name();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Greeting } from './greeting';

@Component({
  selector: 'app-root',
  imports: [Greeting],
  template: `<app-greeting name="Ana" />`,
})
export class App {}

The parent passed Ana. The page shows:

Hello, nobody

text was worked out once, from the default, before the parent’s value arrived. It never changes after that.

The fix for all three is the one from Part 5: work out the text with computed. A computed doesn’t run when it’s created. It runs when the template first reads it, and by then the input has its value. It also follows the input if the parent changes it later.

// src/app/greeting.ts
import { Component, computed, input } from '@angular/core';

@Component({
  selector: 'app-greeting',
  template: `<p>{{ text() }}</p>`,
})
export class Greeting {
  readonly name = input.required<string>();
  protected readonly text = computed(() => 'Hello, ' + this.name());
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Greeting } from './greeting';

@Component({
  selector: 'app-root',
  imports: [Greeting],
  template: `<app-greeting name="Ana" />`,
})
export class App {}

The page shows:

Hello, Ana

The same goes for viewChild.required: reading it in a field initializer or the constructor fails the build with NG8118 too, with `search` is a required `viewChild` in the message. Read queries in afterNextRender, afterRenderEffect, a computed, the template or an event handler. All of those run after Angular has created the template, which is when queries get their results. A read hidden inside a method that the constructor calls builds, but fails at runtime with NG0951, Child query result is required but no value is available.

In older code

Before the signal queries, a query was a field with a decorator: @ViewChild('search') search!: ElementRef;. The ! told TypeScript “trust me, this gets a value”, and it got one only by ngAfterViewInit. You’ll also see @ViewChild('search', { static: true }), which filled the field before ngOnInit, for elements not inside a structural directive. @ViewChildren and @ContentChildren gave a QueryList, which you watched with .changes.subscribe(...). Components listed hooks with implements OnInit, OnDestroy and did setup in ngOnInit. Services came in through the constructor: constructor(private destroyRef: DestroyRef) {} means the same as inject(DestroyRef). All of this still works. New code uses viewChild(), afterNextRender, DestroyRef and inject().

Best practices

  • Use computed for anything worked out from inputs. It waits until the input has a value, then follows it. It replaces field initializers that read inputs, and ngOnInit code that copies them.
  • Do DOM work in afterNextRender or afterRenderEffect. The element exists and is up to date there, and the code is skipped on the server. They replace ngAfterViewInit, and setTimeout used to “wait for the DOM”.
  • Register cleanup next to what it cleans up. inject(DestroyRef).onDestroy(...) right after the setInterval or listener. It replaces ngOnDestroy and the fields that carried ids into it.
  • Use viewChild.required when the element is always there. You drop the ?., and an early read becomes a build error instead of a silent undefined.
  • Prefer bindings, inputs and outputs to queries. A query that reaches into a child to read or set its data couples the two. Keep queries for commands like focus, scroll and reset.

Tips and traps

  • Reading a query in the constructor. viewChild gives undefined, and this.search()?.nativeElement.focus() quietly does nothing. Move it into afterNextRender.
  • Reading an input in a field initializer. A required input fails the build with NG8118, or NG0950 at runtime if the read is inside a method. An input with a default silently uses the default. Use computed.
  • afterNextRender or inject() in an event handler. It fails at runtime with NG0203, an injection context error. Save inject(Injector) in a field and pass { injector }, or set it up in the constructor.
  • Measuring in an effect. It runs before the page is updated, so it reads the old size. Use afterRenderEffect.
  • Forgetting cleanup. A timer or window listener outlives its component, with no error. Every setInterval or addEventListener in a component needs an onDestroy that undoes it.
  • Using viewChild for projected content. It finds only the component’s own template, so it stays undefined. Use contentChild.

A component’s template doesn’t exist while its constructor runs; ask for elements after the first render, and clean up in onDestroy.

Exercises

Exercise 1. This search box should have the cursor in it when the page opens. It doesn’t, and there’s no error. The page shows Focused: false. Why? Fix it.

// src/app/app.ts
import { Component, ElementRef, signal, viewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input #search aria-label="Search" (focus)="focused.set(true)" />
    <p>Focused: {{ focused() }}</p>
  `,
})
export class App {
  private readonly search = viewChild<ElementRef<HTMLInputElement>>('search');
  protected readonly focused = signal(false);

  constructor() {
    this.search()?.nativeElement.focus();
  }
}
Focused: false

Exercise 2. A toast is a small message that hides itself after a while. This one starts a timer when it appears. Here the timer just logs, to make it visible. Click Close at once, before the timer fires, and wait a moment. The console shows toast expired, from a toast that no longer exists. Make the toast cancel its timer when it’s removed, and log toast closed when it does.

// src/app/toast.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-toast',
  template: `<p>Saved.</p>`,
})
export class Toast {
  constructor() {
    setTimeout(() => console.log('toast expired'), 300);
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Toast } from './toast';

@Component({
  selector: 'app-root',
  imports: [Toast],
  template: `
    <button (click)="show.set(false)">Close</button>
    @if (show()) {
      <app-toast />
    }
  `,
})
export class App {
  protected readonly show = signal(true);
}
toast expired

setTimeout returns an id, like setInterval. clearTimeout(id) cancels it.

Exercise 3. Without running it, what order are these six lines logged in? App shows one Badge.

// src/app/badge.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-badge',
  template: `<p>Badge</p>`,
})
export class Badge {
  constructor() {
    console.log('Badge constructor');
  }

  ngOnInit() {
    console.log('Badge ngOnInit');
  }

  ngAfterViewInit() {
    console.log('Badge ngAfterViewInit');
  }
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Badge } from './badge';

@Component({
  selector: 'app-root',
  imports: [Badge],
  template: `<app-badge />`,
})
export class App {
  constructor() {
    console.log('App constructor');
  }

  ngOnInit() {
    console.log('App ngOnInit');
  }

  ngAfterViewInit() {
    console.log('App ngAfterViewInit');
  }
}
Answers

1. The constructor runs before the template is drawn, so this.search() is undefined there. The ?. stops at undefined and calls nothing, so there’s no error and no focus. Move the call into afterNextRender. Since the input is always there, viewChild.required lets you drop the ?.:

// src/app/app.ts
import { afterNextRender, Component, ElementRef, signal, viewChild } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <input #search aria-label="Search" (focus)="focused.set(true)" />
    <p>Focused: {{ focused() }}</p>
  `,
})
export class App {
  private readonly search = viewChild.required<ElementRef<HTMLInputElement>>('search');
  protected readonly focused = signal(false);

  constructor() {
    afterNextRender(() => this.search().nativeElement.focus());
  }
}

The page shows:

Focused: true

2. Keep the id, and clear it in onDestroy:

// src/app/toast.ts
import { Component, DestroyRef, inject } from '@angular/core';

@Component({
  selector: 'app-toast',
  template: `<p>Saved.</p>`,
})
export class Toast {
  constructor() {
    const id = setTimeout(() => console.log('toast expired'), 300);
    inject(DestroyRef).onDestroy(() => {
      clearTimeout(id);
      console.log('toast closed');
    });
  }
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Toast } from './toast';

@Component({
  selector: 'app-root',
  imports: [Toast],
  template: `
    <button (click)="show.set(false)">Close</button>
    @if (show()) {
      <app-toast />
    }
  `,
})
export class App {
  protected readonly show = signal(true);
}

Click Close and wait. The console shows only:

toast closed

If the timer fires first, the toast is still there and toast expired is logged as it should be. Clearing a timer that has already run does nothing, so the cleanup is safe either way.

3. Here’s the run, with the same two files:

// src/app/badge.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-badge',
  template: `<p>Badge</p>`,
})
export class Badge {
  constructor() {
    console.log('Badge constructor');
  }

  ngOnInit() {
    console.log('Badge ngOnInit');
  }

  ngAfterViewInit() {
    console.log('Badge ngAfterViewInit');
  }
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Badge } from './badge';

@Component({
  selector: 'app-root',
  imports: [Badge],
  template: `<app-badge />`,
})
export class App {
  constructor() {
    console.log('App constructor');
  }

  ngOnInit() {
    console.log('App ngOnInit');
  }

  ngAfterViewInit() {
    console.log('App ngAfterViewInit');
  }
}
App constructor
Badge constructor
App ngOnInit
Badge ngOnInit
Badge ngAfterViewInit
App ngAfterViewInit

Angular creates a component’s template, and the child components in it, before it calls that component’s hooks. So Badge is built while App‘s template is created, and both constructors come before any ngOnInit. (That’s for a child written directly in the template. A child inside an @if or @for is created later, after the parent’s ngOnInit.) Then it goes top-down: each component’s ngOnInit runs before Angular fills in the values in that component’s template. ngAfterViewInit goes the other way: a parent’s view isn’t finished until its children’s views are, so Badge comes first.

What’s next

We’ve reached into a component’s own elements and cleaned up after it. In Part 11, we’ll write directives: small classes that attach behaviour, like focusing or highlighting, to any element they’re put on.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.