Sub topic 12
Common mistakes and how to avoid them
This chapter assumes you can write @if, @for and @switch blocks, and that you have used signals or the async pipe. It covers the errors that show up most often in code reviews: wrong track choices, falsy aliases, signals that don't narrow, @switch equality, template syntax slips, and leftovers from migrating old templates.
Mistakes with @for
Leaving out track or choosing a bad one
track is mandatory in @for. If you leave it out, the template fails to compile. The compiler can't guess what identifies an item, so you have to say.
The choice of expression decides how much DOM Angular can reuse when the collection changes.
| Expression | Behavior | Use when |
|---|---|---|
| `track item.id` | DOM follows the item, even when it moves or the object is replaced | Items have a stable unique key (most data from an API) |
| `track item` | DOM follows the object reference | The same object instances stay in the array, such as primitives or long-lived objects |
| `track $index` | DOM follows the position | The list is static, or items have no identity and never reorder |
Two warnings help you find mistakes in development mode:
- NG0955 means two items produced the same key. Angular can't tell them apart reliably, so rows may be reused incorrectly. Fix the key (for example, use a real unique id instead of a category name).
- NG0956 means tracking by identity caused the whole collection to be destroyed and re-created. This usually happens when you replace every object with a fresh copy, for instance after refetching from a server. Track by a stable property instead.
Using $index for rows that hold state
With track $index, the DOM node at position 0 always belongs to whatever item is at position 0. If you remove the first item, Angular keeps the first node and destroys the last one. Any state in the nodes, such as text typed into an input, stays at its position instead of moving with the item.
import { Component, signal } from '@angular/core';
interface Row {
id: number;
label: string;
}
@Component({
selector: 'app-rows',
template: `
<button (click)="removeFirst()">Remove first</button>
@for (row of rows(); track row.id) {
<div>
<label>{{ row.label }} <input type="text" /></label>
</div>
}
`,
})
export class RowsComponent {
rows = signal<Row[]>([
{ id: 1, label: 'A' },
{ id: 2, label: 'B' },
{ id: 3, label: 'C' },
]);
removeFirst() {
this.rows.update((rows) => rows.slice(1));
}
}Type something in each input and click the button. With track row.id, the text you typed next to "B" and "C" stays with those rows. Change the expression to track $index and the text stays in the first two positions while the last row disappears.
Mutating the array in place
A signal notifies its consumers only when you set a new value. push, splice and sort change the existing array without replacing it, so the signal doesn't notice.
// Wrong: same array reference, no notification
this.tasks().push({ id: 3, title: 'New' });
// Right: a new array
this.tasks.update((tasks) => [...tasks, { id: 3, title: 'New' }]);With default change detection, the broken version may seem to work, because an event handler triggers a check anyway. It fails with OnPush components and in zoneless applications. Always produce a new array.
Giving @for something it can't iterate
@for accepts arrays and other iterables such as a Set. It doesn't accept an Observable. Pipe it first.
@for (user of users$ | async; track user.id) {
<li>{{ user.name }}</li>
}A plain object isn't iterable either. Convert it with Object.entries(obj) in the component, or use the keyvalue pipe.
Using the wrong alias syntax
Implicit variables begin with $, and you alias them with let. Writing let i = index doesn't work. Write let i = $index. You don't need an alias at all if the name is free: {{ $index }} works directly inside the block.
An inner @for can shadow an outer alias, which breaks references to the outer index. Alias both loops to different names:
@for (row of rows; track row.id; let r = $index) {
@for (cell of row.cells; track cell.id; let c = $index) {
<span>{{ r }}:{{ c }}</span>
}
}Mistakes with @if
Treating a falsy value as "no value"
@if checks truthiness. The values 0, an empty string and NaN all count as false, even though they are real data.
@if (count$ | async; as count) {
<p>{{ count }} items</p>
} @else {
<p>Loading...</p>
}If count$ emits 0, the user sees "Loading..." forever. Compare explicitly instead:
@if ((count$ | async) !== null; as hasCount) {
<p>Loaded</p>
}An even simpler fix is to wrap the value in an object, such as { count: 0 }, which is always truthy.
Expecting a signal call to narrow its type
TypeScript narrows a variable after a check, but it doesn't narrow a function call. The template type checker works the same way.
import { Component, signal } from '@angular/core';
interface User {
name: string;
}
@Component({
selector: 'app-greeting',
template: `
@if (user(); as u) {
<p>Hello, {{ u.name }}</p>
}
`,
})
export class GreetingComponent {
user = signal<User | null>(null);
}Writing {{ user().name }} inside @if (user()) fails under strict templates, because user() is still User | null on the second call. The alias u has the narrowed type User. This is the main practical reason to use as with signals.
Using an alias outside its block
The alias exists only inside the @if block that declares it. The @else branch can't see it. This makes sense, because the alias is falsy there. If the @else branch needs the original value, read the signal or observable again, or restructure the template.
Mistakes with @switch
@switch compares with strict equality (===). The string '1' doesn't match the number 1.
@switch (code()) {
@case (1) { <p>One</p> }
@case ('1') { <p>String one</p> }
@default { <p>Unknown</p> }
}The other rules to remember:
- Only the first matching
@caserenders. There is no fall-through, so you don't writebreak. - A
@casetakes exactly one value. You can't list several values like@case ('a', 'b'). Use@ifwith a condition such as['a', 'b'].includes(x), or duplicate the content in a child component. - If nothing matches and there is no
@default, nothing renders. Add@defaultwhen an unexpected value should show something. @switchisn't a range test. For comparisons such asscore > 90, use@ifand@else if.
Template syntax mistakes
The characters @, { and } have meaning in templates now. A literal @ followed by a word is read as the start of a block.
<!-- Error: Angular reads "@example" as an incomplete block -->
<p>Write to [email protected]</p>
<!-- Correct: use HTML entities -->
<p>Write to support@example.com</p>
<p>Curly braces: { and }</p>Other syntax slips:
- It is
@else if (...)with a space, not@elseif. @emptybelongs only after an@forblock. It has no meaning after@if.- Blocks aren't attributes. You can't write
<li @for="...">. The block wraps the element. - Each block needs braces, even for a single element.
Leftovers from migration
After you run ng generate @angular/core:control-flow, check three things:
- Unused imports.
NgIf,NgForandNgSwitchstay in a standalone component'simportsarray until you delete them. Recent Angular versions warn about unused standalone imports. - Defaults the schematic had to invent.
*ngForwithouttrackBymigrates totrack $index. That is safe but often not what you want. Replace it with a stable key. - Behavior differences. An
*ngIfhost element is replaced by a block with no wrapper. If a CSS selector relied on theng-templatestructure, check the layout.
The diagram shows how to pick a track expression.
Exercise
A list of products uses @for (p of products(); track $index). Each row contains a text input for a note. After a user deletes the first product, the note they typed for the second product appears next to the third product. What is the cause, and what is the fix?
Show answer
With track $index, Angular reuses DOM nodes by position. Deleting the first product removes the last DOM row, and the remaining rows keep their old input state, which now sits next to different products. Track by a stable unique key instead, such as track p.id, so each DOM row follows its product.
Exercise
@if (total$ | async; as total) { <p>Total: {{ total }}</p> } @else { <p>Loading...</p> } shows "Loading..." even after the server returns a total of 0. Why, and how would you fix it?
Show answer
@if tests truthiness, and 0 is falsy, so the @else branch renders. Compare against the "not loaded" value explicitly, for example (total$ | async) !== null, or emit an object such as { total: 0 }, which is always truthy.
Exercise
A template shows @switch (level()) { @case ('1') { ... } }, where level is a signal<number>. The case never renders. Why?
Show answer
@switch compares with strict equality. The number 1 isn't === to the string '1'. Use @case (1).