Sub topic 12
Common mistakes and how to avoid them
This chapter assumes you know TypeScript, Angular components and templates, and have used @if, @for, and @switch at a basic level. It covers the errors that show up most often and how to fix each one.
Mistake 1: A missing or unstable track expression
@for requires a track expression. Leaving it out is a compile error. A subtler mistake is choosing a poor one.
track $indexties DOM nodes to positions. If you insert or remove an item at the start of the list, every node after it is reused for different data. This can reset input focus and restart animations.track itemuses object identity. If you replace objects with fresh copies (for example after an HTTP refresh), Angular destroys and recreates every node.track item.idfollows a stable, unique key. This is the right default for data that has an ID.
import { Component, signal } from '@angular/core';
interface Task {
id: number;
title: string;
}
@Component({
selector: 'app-tasks',
template: `
<ul>
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
}
</ul>
`,
})
export class TasksComponent {
tasks = signal<Task[]>([{ id: 1, title: 'Write spec' }]);
}Use track $index only for lists that never reorder and hold no per-item state.
Duplicate keys cause a different problem. If two items share an id, Angular cannot tell them apart and may reuse the wrong nodes. Make sure the key is unique.
Mistake 2: Forgetting the `@empty` block
Without @empty, an empty list renders nothing, so the user sees a blank area. Add the fallback so the page explains itself.
@for (task of tasks(); track task.id) {
<li>{{ task.title }}</li>
} @empty {
<li>No tasks yet.</li>
}@empty must come directly after the closing brace of @for.
Mistake 3: Expecting `@switch` to fall through
@switch compares with strict equality (===). It renders only the first matching @case, and it does not fall through to the next case, so there is no break to write. Two consequences follow:
- A string
'1'does not match a number1. Check that the types agree. - You cannot stack cases to share one template. Write the shared content in a child component, or use
@ifwith||.
Add @default to cover every other value. Without it, an unmatched value renders nothing.
Mistake 4: Using the old directive syntax inside a block
*ngIf and *ngFor still work, but they need NgIf and NgForOf in the component's imports. The built-in blocks need no import. Mixing them in one template makes it hard to read and easy to break.
A related error is writing @else if as one word, @elseif. The correct form has a space.
@if (count() > 10) {
<p>Many</p>
} @else if (count() > 0) {
<p>Some</p>
} @else {
<p>None</p>
}Mistake 5: Subscribing twice to an observable
Calling async twice in a template creates two subscriptions, which can mean two HTTP requests. Use as to subscribe once and reuse the result.
import { Component } from '@angular/core';
import { AsyncPipe } from '@angular/common';
import { Observable, of } from 'rxjs';
interface User {
name: string;
}
@Component({
selector: 'app-profile',
imports: [AsyncPipe],
template: `
@if (user$ | async; as user) {
<h2>{{ user.name }}</h2>
} @else {
<p>Loading profile...</p>
}
`,
})
export class ProfileComponent {
user$: Observable<User> = of({ name: 'Ada' });
}The alias exists only inside the @if block. It is not visible in the @else branch.
Remember also that @if checks truthiness. A value of 0 or an empty string counts as false, so @if (count()) hides the block when the count is zero.
Mistake 6: Using `@for` variables outside the block
$index, $first, $last, $even, and similar variables exist only inside the @for block. To use one in a nested block, alias it with let, because an inner @for has its own $index.
@for (row of rows(); track row.id; let rowIndex = $index) {
@for (cell of row.cells; track cell.id) {
<span>{{ rowIndex }}-{{ $index }}</span>
}
}Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Inputs lose focus after list changes | `track $index` or `track item` | Track a stable ID |
| Blank area for empty data | No `@empty` | Add an `@empty` block |
| `@case` never matches | Type mismatch (`'1'` vs `1`) | Align the types |
| Two network requests | Two `async` pipes | Use `as` in `@if` |
| Block hidden when value is `0` | Truthiness check | Compare explicitly, such as `count() !== undefined` |
Exercise
A list of users is reloaded from the server every 30 seconds. Each reload returns new objects with the same id values. A search input inside each row keeps losing focus after the reload. What is the likely cause, and what is the fix?
Show answer
The template probably uses track user (object identity) or track $index. New objects have new identities, so Angular recreates every row. Change it to track user.id so Angular reuses the existing DOM nodes for matching IDs.
Exercise
Why does @switch (value()) with @case (1) not match when value() returns the string '1'?
Show answer
@switch compares with strict equality (===), and '1' is not strictly equal to 1. Make the types agree, either by changing the case to @case ('1') or by converting the value.