Angular Templates: Structural Directives

⭐ What Are Structural Directives in Angular?

Structural directives change or control the structure of the DOM.

Examples:

  • *ngIf

  • *ngFor

  • *ngSwitchCase

They all use micro-syntax, a special shorthand language inside templates.


🎯 What is Micro-Syntax?

Micro-syntax is the short, compact format Angular lets you write with structural directives.

For example:


is a shorthand for:


Micro-syntax = short form
Angular converts it into long <ng-template> form internally.


🧩 *1️⃣ Micro-Syntax for ngIf

Basic:


With else:


 

What Angular actually expands to:



🧩 *2️⃣ Micro-Syntax for ngFor

Basic:


 

Micro-syntax keywords:

  • let β†’ create local variables

  • of β†’ loop over list

  • index, first, last, even, odd β†’ context variables

Full micro-syntax:


Expanded form (Angular internally does this):



🧩 *3️⃣ Micro-Syntax for ngSwitch

Usage:


Angular converts each structural directive into an <ng-template> behind the scenes.


⭐ General Rules of Structural Directive Micro-Syntax

βœ” Rule 1: * always turns element into <ng-template>

Example:


Becomes:



βœ” Rule 2: You can use semicolons (;) to separate instructions

*ngFor="let item of items; let i = index; let e = even"

βœ” Rule 3: Use let to define template variables

let item = contextVariable

βœ” Rule 4: Use keyword as to give alias


Same as:



πŸŽ‰ Example: Combined Micro-Syntax (Advanced)


Angular internally treats them as nested <ng-template>.


βœ”οΈ Summary Table

Structural Directive Micro-syntax Meaning
*ngIf="a; else b" If a true β†’ show block; else β†’ template b
*ngFor="let x of list; let i=index" Loop over list, create local variables
*ngIf="value as v" Creates alias v referencing the value

🎯 Summary in One Line

Micro-syntax is Angular’s shorthand way of writing structural directives, which Angular expands into <ng-template> code internally.

You may also like...