Sub topic 15
Common pitfalls and how to avoid them
This chapter assumes you know the hook order, ngOnInit, ngOnDestroy, and basic RxJS subscriptions. It covers the lifecycle mistakes that show up most often and the fix for each.
Reading inputs in the constructor
Inputs are not set when the constructor runs. Angular creates the instance first, then assigns inputs, then calls ngOnChanges and ngOnInit. Code that reads this.userId in the constructor sees the default value.
Put work that depends on inputs in ngOnInit, or in ngOnChanges if it must rerun when the input changes. Keep the constructor for dependency injection and simple field setup.
Reading view queries too early
@ViewChild results are not available in ngOnInit. The view has not been created yet, so the property is undefined. Use ngAfterViewInit for the first safe access.
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();
}
}Elements inside conditional blocks may not exist yet even then. Check for undefined before using them.
ExpressionChangedAfterItHasBeenChecked
In development mode, Angular checks every binding a second time after the first pass. If a value differs between the two passes, it throws ExpressionChangedAfterItHasBeenCheckedError.
The usual cause is changing state that a parent template has already rendered. A child that updates a parent's field in ngAfterViewInit is a typical case.
Ways to fix it:
- Compute the value earlier, for example in
ngOnInit. - Move the shared state into a signal or a service, so Angular schedules a new update.
- As a last resort, defer the change to a later task. This hides a design problem, so prefer the first two options.
Heavy work in checked hooks
ngDoCheck, ngAfterContentChecked, and ngAfterViewChecked run on every change detection pass. That can mean many times per second. Expensive loops, deep comparisons, or HTTP calls placed there slow the whole application.
Keep these hooks cheap. Compare a single value, set a flag, or move the work to an event handler or a computed signal.
Forgetting to clean up
A subscription to a long-lived source keeps running after the component is gone. This leaks memory and keeps callbacks firing against a destroyed view. The classic fix is to unsubscribe in ngOnDestroy.
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, interval } from 'rxjs';
@Component({
selector: 'app-clock',
standalone: true,
template: `<p>Seconds: {{ seconds }}</p>`,
})
export class ClockComponent implements OnInit, OnDestroy {
seconds = 0;
private subscription?: Subscription;
ngOnInit(): void {
this.subscription = interval(1000).subscribe(() => this.seconds++);
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
}takeUntilDestroyed with DestroyRef removes the need for the extra field and method. Timers, event listeners added with addEventListener, and manual DOM observers need the same cleanup.
Touching the DOM during server rendering
Code that uses window, document, or measures element sizes fails when the page is rendered on the server. Register that work with afterNextRender so it only runs in the browser.
import { Component, afterNextRender } from '@angular/core';
@Component({
selector: 'app-measure',
standalone: true,
template: `<div>Content to measure</div>`,
})
export class MeasureComponent {
constructor() {
afterNextRender(() => {
console.log('Rendered in the browser; safe to touch the DOM');
});
}
}Summary table
| Symptom | Likely cause | Fix |
|---|---|---|
| Input is empty at startup | Read in the constructor | Use `ngOnInit` or `ngOnChanges` |
| View query is `undefined` | Read in `ngOnInit` | Use `ngAfterViewInit` |
| ExpressionChanged error | State changed after the check | Set it earlier or use signals |
| Slow application | Heavy code in checked hooks | Keep hooks cheap |
| Timer keeps running | Missing cleanup | `ngOnDestroy` or `takeUntilDestroyed` |
| Crash on server | Direct DOM access | `afterNextRender` |
Exercise
A component calls this.box.nativeElement.focus() inside ngOnInit and throws because box is undefined. Which hook should it use, and why?
Show answer
It should use ngAfterViewInit. View queries are resolved only after Angular creates the component's view, which happens after ngOnInit.
Exercise
Why is a database lookup inside ngDoCheck a poor choice?
Show answer
ngDoCheck runs on every change detection pass, so the lookup would repeat very often and slow the application. Move it to an event handler or run it only when a specific input changes.