Sub topic 15
Common pitfalls and how to avoid them
This chapter assumes you know the hooks and their order from the earlier chapters, and that you can read basic RxJS and signal code. Most lifecycle bugs come from running code too early, too late, too often, or never. The examples use Angular 19 or later, where afterNextRender and signal queries are stable.
Reading inputs in the constructor
Angular creates the component with new before it binds any inputs. In the constructor, an input still holds its default value.
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-profile',
standalone: true,
template: `<p>{{ label }}</p>`,
})
export class ProfileComponent {
@Input() userId = '';
label = '';
constructor() {
// Bug: userId is still '' here.
this.label = 'User ' + this.userId;
}
}The fix is to move the logic to ngOnInit, which runs once after the first input binding. If the input can change later, use ngOnChanges or a computed signal. Keep the constructor for dependency injection and for registering things that need an injection context, such as afterNextRender or effect.
Expecting ngOnChanges to see everything
ngOnChanges runs only when a template binding assigns a new value to an input. It misses three cases:
- In-place mutation. If a parent does
items.push(x)on the same array, the reference is unchanged andngOnChangesdoes not fire. Pass a new array or object, or usengDoCheckwith a differ. - Programmatic assignment. In a test,
fixture.componentInstance.userId = 'a'does not callngOnChanges. Usefixture.componentRef.setInput('userId', 'a'), which behaves like a template binding. - No bound inputs. A component with no bound inputs never receives
ngOnChanges.
Reading view queries too early
A @ViewChild result is not available at every point. Inside a conditional block such as @if, the element does not exist until that block renders. In the example below, both hooks log undefined on the first pass because open starts as false.
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'app-panel',
standalone: true,
template: `
<button (click)="open = !open">Toggle</button>
@if (open) {
<input #field />
}
`,
})
export class PanelComponent implements OnInit, AfterViewInit {
@ViewChild('field') field?: ElementRef<HTMLInputElement>;
open = false;
ngOnInit(): void {
console.log('ngOnInit', this.field); // undefined
}
ngAfterViewInit(): void {
console.log('ngAfterViewInit', this.field); // undefined: block not rendered yet
}
}A signal query solves this because it updates whenever the element appears or disappears. An effect can then react to it.
import { Component, ElementRef, effect, viewChild } from '@angular/core';
@Component({
selector: 'app-panel-signal',
standalone: true,
template: `
<button (click)="open = !open">Toggle</button>
@if (open) {
<input #field />
}
`,
})
export class PanelSignalComponent {
open = false;
field = viewChild<ElementRef<HTMLInputElement>>('field');
constructor() {
effect(() => {
this.field()?.nativeElement.focus();
});
}
}ExpressionChangedAfterItHasBeenChecked
In development mode, Angular checks every binding twice. After the normal pass, it runs a second pass to confirm that no value changed. If a value differs, it throws NG0100: ExpressionChangedAfterItHasBeenChecked. Production builds skip this check, but the screen can still show stale data.
The usual cause is changing a bound value after Angular has already rendered it in the same pass. This often happens in ngAfterViewInit, ngAfterViewChecked, or a child that updates its parent.
import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-height-bug',
standalone: true,
template: `<div #box>Hello</div><p>Height: {{ height }}</p>`,
})
export class HeightBugComponent implements AfterViewInit {
@ViewChild('box') box!: ElementRef<HTMLElement>;
height = 0;
ngAfterViewInit(): void {
// The binding was rendered as 0. Now it is not 0, so NG0100 is thrown.
this.height = this.box.nativeElement.offsetHeight;
}
}The fix is to measure after rendering and write to a signal. Angular then schedules a fresh update instead of contradicting the pass that just finished.
import { Component, ElementRef, afterNextRender, signal, viewChild } from '@angular/core';
@Component({
selector: 'app-height-fixed',
standalone: true,
template: `<div #box>Hello</div><p>Height: {{ height() }}</p>`,
})
export class HeightFixedComponent {
box = viewChild.required<ElementRef<HTMLElement>>('box');
height = signal(0);
constructor() {
afterNextRender(() => {
this.height.set(this.box().nativeElement.offsetHeight);
});
}
}Try these remedies in order:
- Compute the value earlier, in
ngOnInit,ngOnChangesor acomputedsignal, so it is final before rendering. - Move browser measurement into a render hook and store the result in a signal.
- Restructure the data flow so a child does not change state its parent has already rendered. Use an output event or a shared service with signals.
- As a last resort, call
ChangeDetectorRef.detectChanges()after the change. Avoid wrapping the assignment insetTimeout, because that hides the ordering problem and adds an extra change detection cycle.
Heavy work in hooks that run constantly
ngDoCheck, ngAfterContentChecked and ngAfterViewChecked run on every change detection pass. In a busy application that can be many times per second. Sorting a list, calling a server, or walking the DOM in these hooks makes the whole page slow.
- Compare cheaply, for example with
===on a few fields, and do the real work only when something changed. - Prefer
ngOnChanges,computedoreffectwhen you can. They run only when their inputs change. - Never write to state that is bound in the template from a
Checkedhook. It is the most reliable way to trigger NG0100 or a loop.
Forgetting cleanup
Anything that outlives the component keeps running after it is destroyed. The component also stays in memory because the callback references it.
| Resource | Cleanup |
|---|---|
| RxJS subscription | `takeUntilDestroyed(destroyRef)` or `unsubscribe()` in `ngOnDestroy` |
| `setInterval` or `setTimeout` | `clearInterval` or `clearTimeout` in `ngOnDestroy` |
| `addEventListener` on `window` or `document` | `removeEventListener` with the same function reference |
| Third-party widget or chart | Call its `destroy()` method |
Listener cleanup trips people up because a new arrow function is a different reference each time. Store the handler in a property.
import { Component, OnDestroy, OnInit } from '@angular/core';
@Component({
selector: 'app-resize-watcher',
standalone: true,
template: `<p>Width: {{ width }}</p>`,
})
export class ResizeWatcherComponent implements OnInit, OnDestroy {
width = 0;
private readonly onResize = () => {
this.width = window.innerWidth;
};
ngOnInit(): void {
this.onResize();
window.addEventListener('resize', this.onResize);
}
ngOnDestroy(): void {
window.removeEventListener('resize', this.onResize);
}
}Touching the DOM during server-side rendering
On the server there is no window, document or real element layout. Code in a constructor or ngOnInit that reads window.innerWidth fails during server rendering with a ReferenceError. Put browser-only work in afterNextRender or afterRender. Those hooks never run on the server.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Input is empty or default | Read in the constructor | Use `ngOnInit` or `ngOnChanges` |
| `ngOnChanges` silent | Object mutated in place, or input set in a test directly | Pass a new reference, or use `setInput` |
| Query is `undefined` | Element inside `@if`, or hook too early | Signal query, or `ngAfterViewInit` |
| NG0100 | State changed after rendering | Compute earlier, or use a render hook with a signal |
| Page slows down | Heavy work in `ngDoCheck` or `Checked` hooks | Cheap comparisons, or `computed` |
| Memory grows, timers keep firing | No cleanup | `DestroyRef` or `ngOnDestroy` |
Exercise
A component sets this.count = this.items.length inside ngAfterViewChecked, and count is shown in its template. In development mode it throws NG0100. Why, and what is the simplest fix?
Show answer
ngAfterViewChecked runs after Angular has rendered the template, so count is changed after its binding was already checked. The dev-mode second pass finds a different value and throws. The simplest fix is to remove the assignment and use a computed signal such as count = computed(() => this.items().length), so the value is final before rendering.
Exercise
A parent adds a new item with this.items.push(newItem) on an array it passes to a child's @Input() items. The child's ngOnChanges never fires. Why, and how can the parent fix it?
Show answer
ngOnChanges fires only when the bound reference changes, and push mutates the same array. The parent should pass a new array, for example this.items = [...this.items, newItem].