Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 74 ยท Practice and Review

Common Mistakes and Pitfalls

The Angular mistakes beginners and teams keep making - mutated signals, missing track, leaked subscriptions, ExpressionChanged errors, effect misuse and RxJS overuse - with runnable demos.

Most Angular bugs are not exotic. They are the same dozen mistakes, made by beginners and experts alike, because each one looks reasonable when you write it. A list that does not update, a screen that keeps changing after a component is gone, an error with a code like NG0100 that you have never seen: nearly all of them trace back to a small misunderstanding of how Angular decides that something changed.

This lesson walks through the most common ones. For each, you see what goes wrong, why, and the fix. Five of them come with a runnable demonstration that reproduces the bug with a small stand-in, so you can watch it happen instead of taking our word for it.

Real versus stand-in. The typescript and html blocks are real Angular code and read-only, because this site cannot run the Angular compiler. The runnable examples are stand-ins: a tiny signal and computed, a keyed list renderer, an Observable-like subject, a mock change-detection pass and an effect queue. They are simplified models of the mechanism, not Angular itself, and print deterministic output.

Mistake 1: mutating a signal's value

A signal tells its readers about a change when you call set() or update() with a different value. It compares the new value to the old one with Object.is. If you change the inside of the same array or object, the reference is unchanged, so nobody is told.

TypeScript
// Wrong: same array, same reference. computed() and the template never notice.
this.todos().push(newTodo);
this.user().name = 'Grace';

// Right: create a new array or object.
this.todos.update(list => [...list, newTodo]);
this.user.update(u => ({ ...u, name: 'Grace' }));

A good habit is to type collections as readonly Todo[], so TypeScript rejects push for you. You can also make the signal itself read-only for outside code with asReadonly().

TypeScript Mutation versus a new value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first read of count is cached. The push changes the array but the reported count stays 0, because count was never told to recompute. Only the update with a new array repairs it, and it then counts both items (x and y). The same happens with the object: the greeting keeps saying "Ada" until a new object is set.

Mistake 2: missing or wrong track in @for

@for requires a track expression, and the choice matters. It tells Angular which row is which when the list changes, so it can reuse DOM nodes (and everything living in them: typed text, focus, scroll position, component state) instead of rebuilding.

HTML
<!-- Fine for a list that never reorders or loses items from the middle -->
@for (tag of tags(); track $index) { ... }

<!-- Usually right: a stable identity from the data -->
@for (todo of todos(); track todo.id) { ... }

<!-- Risky: object identity changes whenever you reload from the server -->
@for (todo of todos(); track todo) { ... }

With track $index, the row at position 0 is "row 0" forever. Remove the first item and Angular reuses row 0 for what used to be row 1, keeping row 0's typed text. With track todo after a refresh that creates new objects, every row looks new, so every row is destroyed and rebuilt, losing focus and wasting time. The stand-in below reconciles a list the way the idea works and shows both failures.

TypeScript What track decides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read the two blocks of output. With track $index, after removing Ada the row labelled Grace still carries Ada's typed address: the DOM row stayed, only its label changed. With track item.id the typed text leaves with Ada, and Grace keeps her own row. The last two lines show why tracking by object identity is wasteful after a refresh.

Mistake 3: subscribing without cleanup

An Observable you subscribe to keeps your callback alive until it completes or you unsubscribe. HttpClient requests complete by themselves, but streams such as interval, a Subject, router events or valueChanges do not. If a component subscribes and is later destroyed, the callback keeps running and keeps the component in memory (a leak), and may update something that is no longer on screen.

TypeScript
// Wrong: runs for the lifetime of the page
constructor() {
  this.clock.ticks$.subscribe(n => this.ticks.set(n));
}

// Right 1: tie the subscription to the component's lifetime
constructor() {
  this.clock.ticks$.pipe(takeUntilDestroyed()).subscribe(n => this.ticks.set(n));
}

// Right 2: let Angular manage it
readonly ticks = toSignal(this.clock.ticks$, { initialValue: 0 });
HTML
<!-- Right 3: the async pipe subscribes and unsubscribes with the view -->
<p>{{ ticks$ | async }}</p>

takeUntilDestroyed() called without an argument must run in an injection context, such as a constructor or field initializer; elsewhere pass a DestroyRef. See Signals and RxJS Interop.

TypeScript A leaked subscription

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

After both widgets are destroyed, one listener remains: the leaky widget's. Tick 2 still reaches it. In a real app this means memory that is never freed and handlers that update components nobody can see.

Mistake 4: ExpressionChangedAfterItHasBeenChecked (NG0100)

In development mode, Angular runs change detection and then runs it again to verify that nothing changed during the first pass. If a binding gave one value when it was checked and a different one a moment later, you see NG0100: ExpressionChangedAfterItHasBeenChecked. The error exists because the screen would be showing a value that no longer matches your state.

Typical causes: a child component or lifecycle hook (such as ngAfterViewInit) changes state that a parent has already rendered; a getter that returns a new value on every call (new Date(), a random number); or state that is changed in the middle of a check.

flowchart TD
  A["Check the template<br/>(parent binding reads title)"] --> B["Run lifecycle hooks<br/>(ngAfterViewInit changes title)"]
  B --> C{"Development mode:<br/>check once more"}
  C -->|"title is the same"| D["Fine"]
  C -->|"title changed"| E["NG0100 error"]

The extra verification pass exists only in development mode. It catches state changes that arrived too late for the first check.

The fixes follow one idea: change state before the template that shows it is checked, or after the pass is finished.

TypeScript
// Wrong: changes parent state after the parent's template was already checked
ngAfterViewInit(): void {
  this.parent.title.set('Loaded');
}

// Better: set it early
ngOnInit(): void {
  this.parent.title.set('Loaded');
}

// Better still: derive it instead of copying it
readonly title = computed(() => (this.data.isLoading() ? 'Loading' : 'Loaded'));

If the update really must happen after rendering (for example, after measuring an element), use afterNextRender or schedule it, so it does not run inside the checked pass. Do not "fix" NG0100 by wrapping everything in setTimeout without understanding why; derive state where you can.

TypeScript A mock change-detection pass with a verification step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Changing the state early works. Changing it late throws in development mode; in production mode there is no second look, so the user silently sees stale text, which is why the check is valuable. Deferring the change until the pass is over is also legal, and shows the new value on the next pass.

Mistake 5: effects used for derived state

An effect() is for side effects: talking to something outside the signal graph, such as logging, analytics, drawing on a canvas, or syncing with a non-Angular library. Using an effect to copy one signal into another is a smell, for two reasons. The copy lags behind (effects run later, not at the moment of the change), and the dependency between the two values is hidden.

TypeScript
// Wrong: fahrenheit lags and the link is hidden
readonly celsius = signal(20);
readonly fahrenheit = signal(68);
constructor() {
  effect(() => this.fahrenheit.set((this.celsius() * 9) / 5 + 32));
}

// Right
readonly celsius = signal(20);
readonly fahrenheit = computed(() => (this.celsius() * 9) / 5 + 32);

An effect that reads and writes the same signal can retrigger itself again and again. The stand-in below uses an effect queue that is flushed explicitly, like a change-detection pass does, to show the lag and the runaway case.

TypeScript Effect copy versus computed, and a self-triggering effect

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The computed value is correct at every moment. The effect copy shows 0 before the first flush and still shows the old 68 right after set(100), until the next flush. The self-triggering effect keeps counting until the safety limit stops it; real Angular would not stop it for you, so never write back to a signal you read in the same effect.

Mistake 6: using RxJS where a signal is enough

Observables are excellent for events over time: typing with debounce, WebSocket messages, cancellable requests, combining streams. They are heavy for plain state such as "is the menu open" or "which tab is selected".

TypeScript
// Too much ceremony for a boolean
private readonly open = new BehaviorSubject(false);
readonly open$ = this.open.asObservable();
toggle(): void { this.open.next(!this.open.value); }
// template: @if (open$ | async) { ... }

// A signal says the same thing directly
readonly open = signal(false);
toggle(): void { this.open.update(v => !v); }
// template: @if (open()) { ... }

Another RxJS mistake is nested subscribes: calling subscribe inside another subscribe callback. They are hard to cancel and hard to read. Use a flattening operator instead:

TypeScript
// Wrong
this.route.paramMap.subscribe(params => {
  this.api.load(params.get('id')!).subscribe(item => this.item.set(item));
});

// Right: switchMap cancels the old request when the id changes
this.route.paramMap.pipe(
  map(params => params.get('id')!),
  switchMap(id => this.api.load(id)),
  takeUntilDestroyed(),
).subscribe(item => this.item.set(item));
flowchart TD
  Q{"What are you modeling?"} -->|"A value that is always there<br/>(flag, selection, form text)"| S["signal / computed"]
  Q -->|"Events over time<br/>(typing, clicks, sockets)"| R["Observable + operators"]
  Q -->|"One async read<br/>that depends on signals"| X["resource / httpResource"]
  R --> T["toSignal() to show it in the template"]

A rough guide. The two worlds connect with toSignal() and toObservable().

Mistake 7: giant components

A component that has 800 lines, twelve injected services, a template you must scroll through and logic for fetching, validation, formatting and layout is hard to read, test and change. Signs that it should be split:

  • The template has several sections that each only use a few of the fields.
  • You need comments to mark "the cart part" and "the address part".
  • Tests need a long setup because everything depends on everything.

Split by responsibility: a container (smart) component talks to services and holds state; presentational (dumb) components receive data through input() and report actions through output(); logic that is not about the screen moves into services or plain functions. See Project Structure and Best Practices.

More small traps

  • Forgetting the parentheses on a signal in a template or in code: {{ count }} is the function, not the value. Recent compilers warn about it; the fix is {{ count() }}.
  • Calling a method with heavy work in a template: {{ expensive() }} runs on every change-detection pass. Use computed() or a pure pipe for derived values.
  • Using document.querySelector instead of template references and viewChild(), which breaks with server-side rendering and bypasses Angular.
  • Forgetting to import a component, directive or pipe in a standalone component: the compiler reports an unknown element or pipe.
  • Turning off strict mode to silence errors. The errors are usually real; fix the types.
  • Never unsubscribing from valueChanges of a form that outlives the component, or from router events.
  • Putting secrets in client code. Anything shipped to the browser can be read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A component calls this.items().push(x) and the template does not update. Why?

    Signals compare values by reference. Mutating the array in place keeps the same reference. Use update with a new array instead.
  2. 2. What goes wrong with track $index when you remove the first item of a list of inputs?

    With index tracking, row identity is its position. State that lives in the row, like typed text or focus, stays at that position while the data shifts.
  3. 3. Which subscription needs explicit cleanup?

    interval never completes. Use takeUntilDestroyed, toSignal or the async pipe. HttpClient requests complete, and async and toSignal clean up on their own.
  4. 4. When does the NG0100 ExpressionChangedAfterItHasBeenChecked error appear?

    The verification pass runs only in development mode and compares binding values. A change that arrives after a binding was checked makes the values differ.
  5. 5. Why is an effect that copies one signal into another a poor choice?

    Derived values belong in computed(). Effects run later and are meant for side effects outside the signal graph.

Summary

  • Signals notify on a new value: replace arrays and objects instead of mutating them.
  • Always choose track deliberately: a stable id for dynamic lists; $index only for lists that never reorder or lose middle items.
  • Streams that never complete need cleanup: takeUntilDestroyed(), toSignal() or the async pipe.
  • NG0100 means a value changed after it was checked. Set state earlier, derive it with computed(), or defer it until the pass is over.
  • Effects are for side effects; derived state is computed(). Never write a signal you read in the same effect.
  • Use signals for state and RxJS for events over time; flatten nested subscribes with switchMap.
  • Split giant components into containers, presentational components and services.

Next: Angular Interview Questions.