Structural Directives

Structural Directives in Angular: Walk the length of a commercial print bindery and you find a finishing line: signatures and inserts ride a conveyor past a…

The Analogy: A Print Bindery Insert-and-Collate Line

Walk the length of a commercial print bindery and you find a finishing line: signatures and inserts ride a conveyor past a row of stations, and at each station something happens to every copy as it passes. The line does not edit the words on a page - the press already did that - it decides, copy by copy, which physical leaves end up bound into each finished booklet and in what arrangement. Angular's structural directives are exactly these stations: they never change the content of an element, they change whether and how many times the element exists in the DOM at all, which is why each one is written with a leading asterisk to signal that it restructures the layout. An attribute binding like [value] reaches into an element that already exists and changes one of its properties; a structural directive decides whether that element rides the conveyor in the first place, which is a fundamentally different and more powerful operation.

The insert station is *ngIf. For each copy it consults a rule - this coupon leaf only for subscribers in the trial region - and either drops the leaf into the booklet or leaves it out entirely. Crucially it is not sliding a cover over an unwanted page; the page is either physically present or physically absent. *ngIf="isMember" works the same way: when the condition is false the element and its whole subtree are removed from the document, not merely hidden from view, so nothing downstream can touch them.

The collator is *ngFor. Fed a run list of records, it lays down one stamped signature per record - one personalized page for every subscriber on the mailing - so a hundred names produce a hundred leaves cut from a single master. Beside it sits a diverter gate, ngSwitch, which reads a label on each copy and routes it into exactly one finishing lane, letting only the matching branch through and dropping the rest. Together they turn a list and a set of choices into a precise, per-item stack of physical output.

The failure mode is the one that stops the whole line. Because *ngIf truly removes a leaf rather than masking it, any downstream station that assumed the leaf was there - a page-count sensor, a running tally, a saddle-stitch head positioned for that insert - miscounts or jams the instant the condition flips; when all you wanted was to hide the leaf for a moment you should have kept it and covered it, which in Angular is [hidden]. And a collator given no per-record key, Angular's trackBy, cannot tell which signatures are unchanged when the run list is swapped, so it tears down and re-lays the entire stack on every change instead of reusing the leaves that never moved. On a short run nobody notices the wasted motion, but on a long personalized print job the difference between re-laying three unchanged leaves and re-laying thirty thousand is the difference between a smooth line and one that falls hopelessly behind.


Syntax or Core Structure

A structural directive is applied with a leading asterisk, which is shorthand for wrapping the host element in an <ng-template> that Angular stamps into the DOM only when instructed. The two you reach for daily are *ngIf, which includes an element when a condition is truthy, and *ngFor, which repeats an element once per item in a collection. Both are declarative: you state the condition or the source list, and Angular takes responsibility for creating and destroying the underlying nodes at the right moments, so you never write imperative DOM code to add or remove them yourself.

import { Component } from '@angular/core';

@Component({
  selector: 'app-inbox',
  template: `
    <p *ngIf="messages.length === 0">No messages.</p>
    <ul>
      <li *ngFor="let m of messages">{{ m }}</li>
    </ul>
  `
})
export class InboxComponent {
  messages = ['Deploy done', 'Build passed'];
}

Because messages holds two items, the empty-state paragraph is never added to the DOM, and the list stamps one <li> per message. Modelling that inclusion rule and the per-item repeat as plain functions yields the text Angular renders:

Deploy done
Build passed

If the array were emptied instead, the two list items would vanish from the document entirely and the No messages. paragraph would appear in their place - not because anything was toggled with CSS, but because the set of nodes that exists changed. That structural add-and-remove is the behaviour that separates these directives from ordinary attribute bindings.


Technical Depth: How Each Directive Reshapes the DOM

Structural directives share a mental model - they add, remove, or repeat elements - but each has distinct semantics and cost. Knowing exactly which nodes exist after a directive runs is the difference between a snappy list and a mysterious layout bug.

DirectiveEffect on the DOMTypical use
*ngIfAdds or removes the elementShow a block only when a condition holds
*ngForStamps one element per itemRender a list of records
ngSwitchKeeps one branch, drops the restChoose among several templates
[hidden]Keeps the element, toggles CSSCheap show or hide of a light element

*ngIf adds and removes, it does not hide

The single most common misconception is that *ngIf="false" hides an element the way display: none does. It does not. When the condition is false the element, its children, its component instances, and their subscriptions are all destroyed and removed from the DOM; when it becomes true they are created afresh. That makes *ngIf the right tool for expensive subtrees you want gone when unused, but the wrong tool when you must preserve state - a half-filled form, a scroll position, a playing video - across a toggle. For that, bind [hidden] so the node stays alive and only its visibility flips. *ngIf also supports an else clause that names a separate <ng-template> to stamp when the condition is false, which is the idiomatic way to render a loading placeholder or an empty state without writing a second negated *ngIf beside the first.

*ngFor and its context variables

*ngFor exposes handy locals inside the loop: index, first, last, even, and odd. You capture them with the let syntax, as in let i = index, to build numbered lists or stripe alternate rows without storing any extra state on the component. The most important companion, though, is trackBy: a function you supply that returns a stable identity for each item, letting Angular reuse the existing DOM node for an item that is still present instead of destroying and rebuilding it whenever the array reference changes.

@Component({
  selector: 'app-ranked',
  template: `
    <ol>
      <li *ngFor="let name of players; let i = index">
        {{ i + 1 }}. {{ name }}
      </li>
    </ol>
  `
})
export class RankedComponent {
  players = ['Ada', 'Lin', 'Ravi'];
}
1. Ada
2. Lin
3. Ravi

ngSwitch chooses one branch

ngSwitch behaves like a multiway *ngIf. A [ngSwitch] host holds the value under test, and each *ngSwitchCase includes its element only when the case matches, with *ngSwitchDefault catching everything else.

@Component({
  selector: 'app-status',
  template: `
    <div [ngSwitch]="status">
      <span *ngSwitchCase="'ok'">All systems go</span>
      <span *ngSwitchCase="'warn'">Degraded</span>
      <span *ngSwitchDefault>Unknown state</span>
    </div>
  `
})
export class StatusComponent {
  status = 'warn';
}
Degraded

Only the matching branch is ever stamped into the DOM; the other spans do not exist while status is 'warn', which keeps the rendered tree as small as the current state allows.

The asterisk is microsyntax sugar

The leading asterisk is not magic; it is shorthand the template compiler expands for you. <li *ngFor="let m of items"> desugars into an explicit <ng-template ngFor let-m [ngForOf]="items"> wrapping the <li>, and *ngIf="ok" becomes an <ng-template [ngIf]="ok"> wrapper. That single detail explains a rule that otherwise looks arbitrary: you cannot put two structural directives on one element, because each one wants to claim that lone implicit <ng-template>. When a node needs both a condition and a repeat, host one of them on an <ng-container> - a grouping element that takes part in the template but emits no markup of its own - so each directive gets its own template to expand into.

@Component({
  selector: 'app-feed',
  template: `
    <ng-container *ngIf="items.length">
      <article *ngFor="let it of items">{{ it }}</article>
    </ng-container>
  `
})
export class FeedComponent {
  items = ['post-a', 'post-b'];
}

The container's *ngIf guards the whole block, and only if the list is non-empty does the inner *ngFor stamp an <article> per item; the <ng-container> itself leaves no wrapper tag behind:

post-a
post-b

Real World Example: An Order Summary

An order summary is structural directives working together: *ngFor renders each line item, *ngIf reveals a free-shipping banner once the subtotal crosses a threshold, and interpolation prints the total. It is the shape of a thousand real checkout screens. Watching which nodes appear and disappear as the data changes is the clearest way to internalise that these directives operate on the existence of elements, not merely on their appearance.

@Component({
  selector: 'app-order',
  template: `
    <ul>
      <li *ngFor="let it of items">
        {{ it.name }} x{{ it.qty }} = {{ it.qty * it.price }}
      </li>
    </ul>
    <p *ngIf="subtotal >= 50">You qualify for free shipping!</p>
    <p>Subtotal: {{ subtotal }}</p>
  `
})
export class OrderComponent {
  items = [
    { name: 'Cable', qty: 2, price: 8 },
    { name: 'Adapter', qty: 1, price: 40 }
  ];
  get subtotal(): number {
    return this.items.reduce((s, it) => s + it.qty * it.price, 0);
  }
}

With a cable at two units of eight and one adapter at forty, the subtotal is fifty-six, so the banner's condition holds and it joins the DOM just above the total line:

Cable x2 = 16
Adapter x1 = 40
You qualify for free shipping!
Subtotal: 56

Clear the cart and the structural directives run in reverse: items becomes an empty array, so *ngFor stamps no list items at all, the getter returns zero, the banner's *ngIf condition fails, and that paragraph is removed from the document entirely - leaving only the bare subtotal line rather than an empty list full of nothing.

Subtotal: 0

The genuine design flaw is that *ngFor here carries no trackBy. The moment items is replaced with a fresh array - the usual result of re-fetching the cart from a server, even when the contents are identical - Angular has no key to match old rows to new, so it destroys every <li> and rebuilds them all, discarding any per-row DOM state and doing work proportional to the whole list on each refresh. Compounding it, subtotal is a getter invoked twice per change-detection pass, once for the *ngIf and once for the interpolation, and it reduces the entire array both times. On this two-item cart neither cost registers, but on a large order that refreshes often the list rebuild and the repeated reductions become a real source of jank. The fix is to give *ngFor a trackBy keyed on a stable id and to precompute the subtotal into a field updated only when items changes, so structural work happens for genuine changes rather than for every tick of the clock. Both fixes are small, yet skipping them is exactly the kind of omission that passes every test on a two-row demo and only surfaces as sluggishness once real data arrives - which is why trackBy and precomputed derived values are habits worth forming well before you need them.


Common Mistakes

  1. Thinking *ngIf hides an element. A false condition destroys the node and all its state; use [hidden] when the element must survive the toggle.
  2. Putting two structural directives on one element. *ngIf and *ngFor cannot share a host; wrap one in an <ng-container> instead of stacking asterisks.
  3. Omitting trackBy on a changing list. Without a stable key, replacing the array rebuilds every row and loses focus, animation, and scroll state.
  4. Expecting *ngIf to keep component state. A toggled-off component is fully destroyed, so its fields reset to their defaults when it returns.
  5. Forgetting CommonModule. *ngIf, *ngFor, and ngSwitch come from CommonModule; a standalone component that omits it renders nothing and warns.
  6. Mutating an array in place and expecting a refresh. A push on the same reference may not retrigger *ngFor predictably; assign a new array to signal the change.
  7. Using the loop index as a trackBy key. The index shifts when items are inserted or removed, defeating the purpose; track a real identifier.
  8. Overusing *ngIf for trivial toggles. Destroying and recreating a light element on every toggle costs more than a CSS [hidden] would.
  9. Assuming ngSwitch falls through like C. Only the matching *ngSwitchCase is stamped; there is no cascade and no break.

Best Practices

  • Reach for [hidden] or CSS when you only need to show or hide; reserve *ngIf for subtrees genuinely worth creating and destroying.
  • Always give *ngFor a trackBy function keyed on a stable, unique identifier whenever the list can change.
  • Use <ng-container> to host a structural directive without emitting an extra wrapper element into the DOM.
  • Pair *ngIf with its else template reference for clean two-state rendering instead of duplicating the negated condition.
  • Prefer ngSwitch over a ladder of sibling *ngIf blocks when the branches are mutually exclusive.
  • Keep the expression in a structural directive cheap, since it is evaluated on every change-detection pass.
  • Precompute derived lists and totals in the component rather than recomputing them inside the template.
  • Import CommonModule (or the individual directives) in every standalone component that uses structural directives.

Practice Exercises

  1. Render a filtered list. Given an array of tasks, use *ngFor to list them and *ngIf to show a "Nothing to do" message only when the array is empty.
  2. Stripe a table. Use the *ngFor even and odd context variables to apply alternating row labels, and confirm the pattern with a small fixed array.
  3. Build a status pill. Use ngSwitch to render one of four labels from a level string, including a *ngSwitchDefault for unknown values.
  4. Add a trackBy. Take a list bound with *ngFor, add a trackBy keyed on each item's id, and describe what changes when the backing array is replaced with an equal one.