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
β Rule 3: Use let to define template variables
β 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.
