Sub topic 8
Working with the component's own view: the AfterView hooks
This chapter assumes you can write a standalone Angular component, you know how ngOnInit and ngOnChanges behave, and you have a basic idea of how change detection runs. Here you will learn when ngAfterViewInit and ngAfterViewChecked run, what is safe to do in them, and why they are a common source of ExpressionChangedAfterItHasBeenChecked errors.
What "the view" means
A component's view is the DOM that its own template creates. It includes any child components and directives that the template declares. It does not include content that a parent projects in through <ng-content>. Projected content belongs to the AfterContent hooks, which are covered in the previous chapter.
The AfterView hooks tell you that Angular has finished work on this view:
ngAfterViewInit()runs once. It runs after Angular has created the component's view and its child views, and after the first change detection pass over them.ngAfterViewChecked()runs after every change detection pass over the component's view and child views, including the first one.
On the first pass, both run in that order: ngAfterViewInit, then ngAfterViewChecked.
When view queries become available
You reach elements and child components in your own template with view queries: @ViewChild, @ViewChildren, or the signal-based viewChild and viewChildren functions. The timing depends on the query.
| Query | Result available |
|---|---|
| `@ViewChild(..., { static: true })` | Before `ngOnInit`, but only if the target is not inside `@if`, `@for`, or `ng-template` |
| `@ViewChild(...)` (dynamic, the default) | Before `ngAfterViewInit` runs, and updated on every later check |
| `@ViewChildren(...)` | Always dynamic. Available in `ngAfterViewInit`, and the `QueryList` updates when matching elements are added or removed |
| Signal queries (`viewChild`, `viewChildren`) | Read the signal. It holds `undefined` (or an empty array) until the view exists |
Before the view is created, a query holds undefined. The constructor and ngOnInit are too early for any element that sits in a conditional block. For everything else, ngAfterViewInit is the first hook where all dynamic view queries are safe to read.
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-focus-input',
standalone: true,
template: `<input #box type="text" />`,
})
export class FocusInputComponent implements AfterViewInit {
@ViewChild('box') box!: ElementRef<HTMLInputElement>;
ngAfterViewInit(): void {
this.box.nativeElement.focus();
}
}The ! tells TypeScript that Angular will assign the property later. This is accurate only after the view exists, so do not read box in the constructor or ngOnInit.
Where the hooks fall in a pass
The view hooks run after the component's own bindings and all of its children have been processed. Child components finish first, so a parent's ngAfterViewInit runs after every child's ngAfterViewInit.
The consequence is useful. When the parent's ngAfterViewInit runs, each child component in its view is fully initialized. You can read a child's public state through a @ViewChild reference at that point.
Reading a child component
import { AfterViewInit, Component, ViewChild } from '@angular/core';
@Component({
selector: 'app-badge',
standalone: true,
template: `<span>{{ label }}</span>`,
})
export class BadgeComponent {
label = 'ready';
}
@Component({
selector: 'app-panel',
standalone: true,
imports: [BadgeComponent],
template: `<h2>Panel</h2><app-badge />`,
})
export class PanelComponent implements AfterViewInit {
@ViewChild(BadgeComponent) badge!: BadgeComponent;
ngAfterViewInit(): void {
console.log('child label:', this.badge.label);
}
}This works because reading is harmless. The trouble starts when you write.
The ExpressionChangedAfterItHasBeenChecked trap
In development mode, Angular runs a second, read-only pass after each check. It compares every binding value with the value it saw a moment earlier. If a value differs, it throws ExpressionChangedAfterItHasBeenChecked (error NG0100). The reason is that Angular has already rendered the old value, and the DOM would be out of date with your state.
ngAfterViewInit runs after the parent's own bindings have been rendered. If you change a property that the template binds, the template has already shown the old value.
import { AfterViewInit, Component, ViewChild } from '@angular/core';
@Component({
selector: 'app-header-badge',
standalone: true,
template: `<span>{{ label }}</span>`,
})
export class HeaderBadgeComponent {
label = 'ready';
}
@Component({
selector: 'app-broken-panel',
standalone: true,
imports: [HeaderBadgeComponent],
template: `<h2>{{ title }}</h2><app-header-badge />`,
})
export class BrokenPanelComponent implements AfterViewInit {
@ViewChild(HeaderBadgeComponent) badge!: HeaderBadgeComponent;
title = 'Loading';
ngAfterViewInit(): void {
// The template already rendered "Loading". Changing it now throws NG0100 in dev mode.
this.title = this.badge.label;
}
}You have three ways to fix it, listed here from best to worst:
- Restructure so the data flows downward. If the parent needs the value in its own template, let the child expose it as an output or a shared service, or compute the value before the view renders.
- Re-run change detection explicitly after the write. Inject
ChangeDetectorRefand calldetectChanges()right after the assignment. This re-renders the view with the new value, so the verification pass sees consistent data. - Defer the write to a later turn, for example with
Promise.resolve().then(...). This hides the error, but it adds an extra render and makes the order harder to follow. Use it only when the first two do not fit.
import { AfterViewInit, ChangeDetectorRef, Component, ViewChild, inject } from '@angular/core';
@Component({
selector: 'app-fixed-panel',
standalone: true,
imports: [HeaderBadgeComponent],
template: `<h2>{{ title }}</h2><app-header-badge />`,
})
export class FixedPanelComponent implements AfterViewInit {
private readonly cdr = inject(ChangeDetectorRef);
@ViewChild(HeaderBadgeComponent) badge!: HeaderBadgeComponent;
title = 'Loading';
ngAfterViewInit(): void {
this.title = this.badge.label;
this.cdr.detectChanges();
}
}Queries inside conditional blocks
A target inside @if does not exist until its condition is true. A dynamic query returns undefined while the block is absent and picks up the element after Angular renders it. If the condition is false when ngAfterViewInit runs, the query is still empty at that moment.
For queries that may change, use @ViewChildren and subscribe to changes on the QueryList, or use the signal-based viewChildren. Do not assume that a one-time read in ngAfterViewInit stays valid.
import { AfterViewInit, Component, ElementRef, QueryList, ViewChildren } from '@angular/core';
@Component({
selector: 'app-item-list',
standalone: true,
template: `
@for (item of items; track item) {
<li #row>{{ item }}</li>
}
`,
})
export class ItemListComponent implements AfterViewInit {
items = ['a', 'b', 'c'];
@ViewChildren('row') rows!: QueryList<ElementRef<HTMLLIElement>>;
ngAfterViewInit(): void {
console.log('rows at init:', this.rows.length);
this.rows.changes.subscribe(list => console.log('rows now:', list.length));
}
}ngAfterViewChecked: use it sparingly
ngAfterViewChecked runs after every check of the view, and Angular can run checks many times per second in an active app. Code in this hook must be cheap and must not change bound state, or it triggers the error from the previous section. Typical legitimate uses are narrow, such as re-measuring an element after a layout change. Even then, guard the work with a comparison so it does nothing on most passes.
Server-side rendering
ngAfterViewInit runs on the server too. Calling focus(), measuring layout, or using window can fail or return meaningless values there, because no real browser DOM exists. Keep browser-only work in afterNextRender, registered in the constructor, and keep ngAfterViewInit for logic that is safe in both environments.
Summary of rules
- Read view queries in
ngAfterViewInitor later, never in the constructor. - Use
static: trueonly for targets that are not inside@if,@for, orng-template. - Do not change bound state in these hooks without a plan, such as restructuring or
detectChanges(). - Keep
ngAfterViewCheckedcheap or leave it out.
Exercise
A component declares @ViewChild('chart') chart!: ElementRef; where <canvas #chart> sits inside an @if (ready) block. In ngAfterViewInit, this.chart is undefined even though the code is correct. Why, and what is a safe way to get the element when it appears?
Show answer
The @if condition was false when ngAfterViewInit ran, so Angular had not yet created the canvas and the query had nothing to match. The hook runs only once, so it does not see the element later. Use a signal query (viewChild) or @ViewChildren and react to QueryList.changes, or move the drawing code into a child component that renders only when ready is true, so its own ngAfterViewInit runs when the canvas exists.