Skip to the workspace
Pebellslearn by building
Templates and Directives  ›  Lesson

Structural Directives

Structural Directives 12 minStructural directives such as *ngIf and *ngFor add and remove chunks of the page, and the star is shorthand for wrapping the element in an ng-template that the directive stamps out.

angular / Structural Directives

Explore each scene at your own pace.

01 · The rule

The rule

Structural Directives

Open almost any Angular project written before 2024 and you will see stars in the templates: *ngIf, *ngFor. Greenhouse will use the newer built-in blocks, but you need to read the older style fluently, and understanding the star explains what every "show this, repeat that" feature really does.

The rule

A star means "this element is a template the directive stamps out".

A structural directive changes the structure of the page: it adds or removes elements rather than changing how one looks.

<p *ngIf="plants.length === 0">No plants yet.</p>

<li *ngFor="let p of plants; let i = index">
  {{ i + 1 }}. {{ p.name }}
</li>

*ngIf renders the paragraph only while the condition is true. *ngFor renders one <li> per plant. Both come from @angular/common and must be imported (NgIf, NgFor, or the whole CommonModule).

The star is shorthand. Angular rewrites the element into an <ng-template>, a piece of markup that is not shown on its own, and hands it to the directive:

<ng-template [ngIf]="plants.length === 0">
  <p>No plants yet.</p>
</ng-template>

The directive then decides how many copies to stamp into the page: zero or one for ngIf, one per item for ngFor.

Two rules follow:

  • One star per element. Each star wants to wrap the element, and two wrappers on one element are ambiguous. Use <ng-container>, an invisible grouping tag, to carry the second one.
  • An else needs a named template: *ngIf="plants.length; else empty" with <ng-template #empty>...</ng-template>.

Modern Angular replaces these with the built-in @if, @for and @switch blocks, which need no imports and read more clearly. The star directives are marked deprecated in recent versions, but they still work, and you will meet them for years.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.