← Back to Angular, page 3

angular-0046 · Hard senior

What are the most common Angular mistakes in real projects, including ExpressionChangedAfterItHasBeenChecked, template function calls, nested subscribes and mutation, and how do you fix them?

The usual problems are state changed during change detection (NG0100), heavy functions called from templates, subscribe inside subscribe, mutating inputs of OnPush components, missing cleanup, and missing track keys. Each has a direct fix with computed, switchMap, immutable updates, takeUntilDestroyed or toSignal, and a stable track expression.

Full answer

These come up in code reviews again and again.

  1. ExpressionChangedAfterItHasBeenChecked (NG0100). In development mode Angular checks twice. If a value used in a template changes between the two passes, it throws. Typical cause: a child changes parent state in ngAfterViewInit or ngOnInit, after the parent was already rendered. Fix: change the data flow (the parent owns the state and passes it down, or the child emits an event), compute values with computed, or move the change into a later task. Not a fix: hiding the error with setTimeout without understanding the cause, or detectChanges() calls.

  2. Heavy function calls in templates. {{ getTotal() }} runs on every change detection pass. Use a computed signal or a pure pipe.

  3. Nested subscribes. A subscribe inside a subscribe creates callback pyramids, leaks, and race conditions. Use switchMap, concatMap, or forkJoin.

  4. Mutation. Pushing into an array or editing an object that an OnPush child received. The view does not update. Create a new array or object, or use signal update with spread syntax.

  5. Missing cleanup. Subscribing to interval, valueChanges, or router events without takeUntilDestroyed, the async pipe, or toSignal.

  6. Missing or poor track in @for (or trackBy in the legacy *ngFor), causing DOM rebuilds.

  7. Putting logic in components that belongs in services, making testing hard.

  8. Using any. It removes the checks that the typed forms, typed HTTP, and strict templates provide. Turn on strict and strictTemplates.

  9. Importing a whole module or a large library for one function, which inflates the bundle.

  10. Not handling HTTP errors. A one-shot HTTP call needs no unsubscribe, but a failed call still needs a visible message or a fallback.

The example below shows the fixed forms of items 2, 3, 4, and 5 in one component.

typescript
import { HttpClient } from '@angular/common/http';
import { Component, computed, inject, input, signal } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import { catchError, of, switchMap } from 'rxjs';

interface Student {
  id: number;
  name: string;
  marks: number;
}

interface Detail {
  id: number;
  address: string;
}

@Component({
  selector: 'app-student-table',
  template: `
    <p>Average: {{ average() }}</p>
    <button (click)="addStudent()">Add</button>
    @for (s of sorted(); track s.id) {
      <button (click)="selectedId.set(s.id)">{{ s.name }} ({{ s.marks }})</button>
    }
    <p>{{ detail()?.address ?? 'Select a student' }}</p>
  `,
})
export class StudentTableComponent {
  private readonly http = inject(HttpClient);

  readonly students = input.required<Student[]>();
  readonly extra = signal<Student[]>([]);
  readonly selectedId = signal<number | null>(null);

  // Item 2. Old form: {{ getAverage() }} called on every change detection pass.
  readonly all = computed(() => [...this.students(), ...this.extra()]);
  readonly average = computed(() => {
    const list = this.all();
    return list.length ? Math.round(list.reduce((sum, s) => sum + s.marks, 0) / list.length) : 0;
  });
  readonly sorted = computed(() => [...this.all()].sort((a, b) => b.marks - a.marks));

  // Items 3 and 5. Old form: subscribe inside subscribe with no cleanup.
  readonly detail = toSignal(
    toObservable(this.selectedId).pipe(
      switchMap((id) =>
        id === null
          ? of<Detail | null>(null)
          : this.http.get<Detail>(`/api/students/${id}`).pipe(catchError(() => of<Detail | null>(null))),
      ),
    ),
    { initialValue: null },
  );

  // Item 4. Old form: this.extra().push(...) which signals cannot detect.
  addStudent(): void {
    this.extra.update((list) => [...list, { id: 100 + list.length, name: 'New', marks: 50 }]);
  }
}

Angular 20.3, strict template check passes. The comments mark the old form of each pattern, which should not be written in new code.

Key points

  • NG0100 means state changed after it was rendered. Fix the data flow, not the symptom.
  • Replace template function calls with `computed` or a pure pipe.
  • Replace nested subscribes with flattening operators, and clean up with `toSignal` or `takeUntilDestroyed`.
  • Use immutable updates with OnPush and give `@for` a stable `track`.

Common mistakes

  • Fixing NG0100 with `setTimeout` and leaving the real design problem in place.
  • Turning off strict mode when the compiler complains instead of fixing the types.
  • Using `ChangeDetectorRef.detectChanges()` as a general repair tool.

Follow-ups

  • How would you reproduce NG0100 on purpose?
  • Why is a template function call different from a `computed`?
  • Which of these would you flag first in a code review, and why?

Tips

  • Prefer a real story from a review or debugging session in your own words, with the cause and the fix.
  • Always explain why a pitfall happens, not only the fix.
  • Say that you enable strict compiler options so many of these are caught early.

Evaluation rubric

  • Explains NG0100 and its real fixes.
  • Gives correct replacements for common anti-patterns.
  • Shows awareness of strict settings and review habits.