Angular Templates: Structural Directives Micro-syntax
Use *
shorthand for structural directives; Angular expands it to <ng-template>
.
What is the Structural Directives micro-syntax?
*
is shorthand that expands to an underlying<ng-template>
.- Provides context variables (e.g.,
index as i
,else
). - Angular rewrites
*ngIf
,*ngFor
, etc., using this syntax.
Important: In Angular 17+, prefer the new control flow syntax (@if
, @for
, @switch
).
The micro-syntax for *ngIf
/*ngFor
remains supported for existing code. See Control Flow.
When to use the micro-syntax
- With structural directives to add/remove DOM based on state.
- To iterate lists concisely with
*ngFor
. - Use shorthand for readability; use explicit
<ng-template>
when needed.
Example
Use the *
micro-syntax to expand structural directives and expose context variables:
<div *ngIf="ok; else other">OK</div>
<ng-template #other>Not OK</ng-template>
<li *ngFor="let item of items; index as i">{{ i }} {{ item }}</li>
Code explained
*ngIf="ok; else other"
: Renders the block whenok
is truthy; otherwise renders the#other
template.*ngFor="...; index as i"
: Loops overitems
and exposes the zero‑based index asi
.*
shorthand: Angular rewrites*...
into an underlying<ng-template>
.
See Conditional Rendering for *ngIf
and Lists for *ngFor
, micro-syntax (index as i
, else
), and more examples.
Example
Use micro-syntax with *ngIf
and *ngFor
to conditionally render or iterate:
Example
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
template: `
<button (click)="ok = !ok">Toggle</button>
<div *ngIf="ok; else other">OK</div>
<ng-template #other>Not OK</ng-template>
<ul>
<li *ngFor="let item of items; index as i">{{ i }} - {{ item }}</li>
</ul>
`
})
export class App {
ok = true;
items = ['A','B','C'];
}
bootstrapApplication(App);
<app-root></app-root>
Example explained
*
shorthand:*ngIf
and*ngFor
are shorthand that Angular rewrites to an underlying<ng-template>
.*ngIf="ok; else other"
: Renders the block whenok
is true; otherwise renders the template referenced by#other
.*ngFor="let item of items; index as i"
: Iterates the arrayitems
;item
is the current element andi
is the zero-based index.