Built-in Structural Directives

Go back to Tutorial

Structural directives are responsible for HTML layout. They shape or reshape the DOM’s structure, typically by adding, removing, and manipulating the host elements to which they are attached.

As with other directives, you apply a structural directive to a host element. The directive then does whatever it’s supposed to do with that host element and its descendants. Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name as in this example.

src/app/app.component.html (ngif)

<div *ngIf=”hero” class=”name”>{{hero.name}}</div>

No brackets. No parentheses. Just *ngIf set to a string.

You’ll learn in this guide that the asterisk (*) is a convenience notation and the string is a microsyntax rather than the usual template expression. Angular desugars this notation into a marked-up <ng-template> that surrounds the host element and its descendents. Each structural directive does something different with that template.

Three of the common, built-in structural directives—NgIf, NgFor, and NgSwitch…—are described in the Template Syntax guide and seen in samples throughout the Angular documentation. Here’s an example of them in a template:

src/app/app.component.html (built-in)

<div *ngIf=”hero” class=”name”>{{hero.name}}</div>


<li *ngFor=”let hero of heroes”>{{hero.name}}</li>


<div [ngSwitch]=”hero?.emotion”>

<app-happy-hero    *ngSwitchCase=”‘happy'”    [hero]=”hero”></app-happy-hero>

<app-sad-hero      *ngSwitchCase=”‘sad'”      [hero]=”hero”></app-sad-hero>

<app-confused-hero *ngSwitchCase=”‘app-confused'” [hero]=”hero”></app-confused-hero>

<app-unknown-hero  *ngSwitchDefault           [hero]=”hero”></app-unknown-hero>


A directive class is spelled in UpperCamelCase (NgIf). A directive’s attribute name is spelled in lowerCamelCase (ngIf). The guide refers to the directive class when talking about its properties and what the directive does. The guide refers to the attribute name when describing how you apply the directive to an element in the HTML template.


NgIf is the simplest structural directive and the easiest to understand. It takes a boolean expression and makes an entire chunk of the DOM appear or disappear.

src/app/app.component.html (ngif-true)

<p *ngIf=”true”>

Expression is true and ngIf is true.

This paragraph is in the DOM.


<p *ngIf=”false”>

Expression is false and ngIf is false.

This paragraph is not in the DOM.


The ngIf directive doesn’t hide elements with CSS. It adds and removes them physically from the DOM. Confirm that fact using browser developer tools to inspect the DOM.

The top paragraph is in the DOM. The bottom, disused paragraph is not; in its place is a comment about “bindings”.

When the condition is false, NgIf removes its host element from the DOM, detaches it from DOM events (the attachments that it made), detaches the component from Angular change detection, and destroys it. The component and DOM nodes can be garbage-collected and free up memory.

The asterisk (*) prefix

Surely you noticed the asterisk (*) prefix to the directive name and wondered why it is necessary and what it does.

Here is *ngIf displaying the hero’s name if hero exists.

src/app/app.component.html (asterisk)

<div *ngIf=”hero” class=”name”>{{hero.name}}</div>

The asterisk is “syntactic sugar” for something a bit more complicated. Internally, Angular translates the *ngIf attribute into a <ng-template> element, wrapped around the host element, like this.

src/app/app.component.html (ngif-template)

<ng-template [ngIf]=”hero”>

  <div class=”name”>{{hero.name}}</div>


  • The *ngIf directive moved to the <ng-template> element where it became a property binding,[ngIf].
  • The rest of the <div>, including its class attribute, moved inside the <ng-template> element.

The first form is not actually rendered, only the finished product ends up in the DOM.

Angular consumed the <ng-template> content during its actual rendering and replaced the <ng-template> with a diagnostic comment.


The NgFor and NgSwitch… directives follow the same pattern.


Angular transforms the *ngFor in similar fashion from asterisk (*) syntax to <ng-template> element. Here’s a full-featured application of NgFor, written both ways:

src/app/app.component.html (inside-ngfor)

<div *ngFor=”let hero of heroes; let i=index; let odd=odd; trackBy: trackById” [class.odd]=”odd”>

({{i}}) {{hero.name}}


<ng-template ngFor let-hero [ngForOf]=”heroes” let-i=”index” let-odd=”odd” [ngForTrackBy]=”trackById”>

<div [class.odd]=”odd”>({{i}}) {{hero.name}}</div>


This is manifestly more complicated than ngIf and rightly so. The NgFor directive has more features, both required and optional, than the NgIf shown in this guide. At minimum NgFor needs a looping variable (let hero) and a list (heroes).

You enable these features in the string assigned to ngFor, which you write in Angular’s microsyntax.

Everything outside the ngFor string stays with the host element (the <div>) as it moves inside the <ng-template>. In this example, the [ngClass]=”odd” stays on the <div>.

Microsyntax – The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>:


  • The let keyword declares a template input variable that you reference within the template. The input variables in this example are hero, i, and odd. The parser translates let hero, let i, and let odd into variables named, let-hero, let-i, and let-odd.
  • The microsyntax parser takes of, and trackBy, title-cases them (of -> Of, trackBy -> TrackBy), and prefixes them with the directive’s attribute name (ngFor), yielding the names ngForOf and ngForTrackBy. Those are the names of two NgFor input properties . That’s how the directive learns that the list is heroes and the track-by function is trackById.
  • As the NgFor directive loops through the list, it sets and resets properties of its own context object. These properties include index and odd and a special property named $implicit.
  • The let-i and let-odd variables were defined as let i=index and let odd=odd. Angular sets them to the current value of the context’s index and odd properties.
  • The context property for let-hero wasn’t specified. Its intended source is implicit. Angular sets let-hero to the value of the context’s $implicit property which NgFor has initialized with the hero for the current iteration.
  • The API guide describes additional NgFor directive properties and context properties.
  • NgFor is implemented by the NgForOf directive.


These microsyntax mechanisms are available to you when you write your own structural directives. Studying the source code for NgIf and NgForOf is a great way to learn more.

Template input variable – A template input variable is a variable whose value you can reference within a single instance of the template. There are several such variables in this example: hero, i, and odd. All are preceded by the keyword let.

A template input variable is not the same as a template reference variable, neither semantically nor syntactically.

You declare a template input variable using the let keyword (let hero). The variable’s scope is limited to a single instance of the repeated template. You can use the same variable name again in the definition of other structural directives.

You declare a template reference variable by prefixing the variable name with # (#var). A reference variable refers to its attached element, component or directive. It can be accessed anywhere in the entire template.

Template input and reference variable names have their own namespaces. The hero in let hero is never the same variable as the hero declared as #hero.

One structural directive per host element – Someday you’ll want to repeat a block of HTML but only when a particular condition is true. You’ll try to put both an *ngFor and an *ngIf on the same host element. Angular won’t let you. You may apply only one structural directive to an element.

The reason is simplicity. Structural directives can do complex things with the host element and its descendents. When two directives lay claim to the same host element, which one takes precedence? Which should go first, the NgIf or the NgFor? Can the NgIf cancel the effect of the NgFor? If so (and it seems like it should be so), how should Angular generalize the ability to cancel for other structural directives?

There are no easy answers to these questions. Prohibiting multiple structural directives makes them moot. There’s an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an ng-container so you don’t have to introduce extra levels of HTML.

The <ng-template>

The <ng-template> is an Angular element for rendering HTML. It is never displayed directly. In fact, before rendering the view, Angular replaces the <ng-template> and its contents with a comment.

If there is no structural directive and you merely wrap some elements in a <ng-template>, those elements disappear. That’s the fate of the middle “Hip!” in the phrase “Hip! Hip! Hooray!”.

src/app/app.component.html (template-tag)






Angular erases the middle “Hip!”, leaving the cheer a bit less enthusiastic.

A structural directive puts a <ng-template> to work as you’ll see when you write your own structural directive.

Group sibling elements with <ng-container>

There’s often a root element that can and should host the structural directive. The list element (<li>) is a typical host element of an NgFor repeater.


src/app/app.component.html (ngfor-li)

<li *ngFor=”let hero of heroes”>{{hero.name}}</li>

When there isn’t a host element, you can usually wrap the content in a native HTML container element, such as a <div>, and attach the directive to that wrapper.

src/app/app.component.html (ngif)

<div *ngIf=”hero” class=”name”>{{hero.name}}</div>

Introducing another container element—typically a <span> or <div>—to group the elements under a single root is usually harmless. Usually … but not always.

The grouping element may break the template appearance because CSS styles neither expect nor accommodate the new layout. For example, suppose you have the following paragraph layout.

src/app/app.component.html (ngif-span)


I turned the corner

<span *ngIf=”hero”>

and saw {{hero.name}}. I waved


and continued on my way.


You also have a CSS style rule that happens to apply to a <span> within a <p>aragraph.

src/app/app.component.css (p-span)

p span { color: red; font-size: 70%; }

The constructed paragraph renders strangely.

The p span style, intended for use elsewhere, was inadvertently applied here.

Another problem: some HTML elements require all immediate children to be of a specific type. For example, the <select> element requires <option> children. You can’t wrap the options in a conditional <div> or a <span>.

When you try this,

src/app/app.component.html (select-span)


Pick your favorite hero

(<label><input type=”checkbox” checked (change)=”showSad = !showSad”>show sad</label>)


<select [(ngModel)]=”hero”>

<span *ngFor=”let h of heroes”>

<span *ngIf=”showSad || h.emotion !== ‘sad'”>

<option [ngValue]=”h”>{{h.name}} ({{h.emotion}})</option>




the drop down is empty.

The browser won’t display an <option> within a <span>.

<ng-container> to the rescue – The Angular <ng-container> is a grouping element that doesn’t interfere with styles or layout because Angular doesn’t put it in the DOM.

Here’s the conditional paragraph again, this time using <ng-container>.

src/app/app.component.html (ngif-ngcontainer)


I turned the corner

<ng-container *ngIf=”hero”>

and saw {{hero.name}}. I waved


and continued on my way.


It renders properly. Now conditionally exclude a select <option> with <ng-container>.

src/app/app.component.html (select-ngcontainer)


Pick your favorite hero

(<label><input type=”checkbox” checked (change)=”showSad = !showSad”>show sad</label>)


<select [(ngModel)]=”hero”>

<ng-container *ngFor=”let h of heroes”>

<ng-container *ngIf=”showSad || h.emotion !== ‘sad'”>

<option [ngValue]=”h”>{{h.name}} ({{h.emotion}})</option>




The drop down works properly. The <ng-container> is a syntax element recognized by the Angular parser. It’s not a directive, component, class, or interface. It’s more like the curly braces in a JavaScript if-block:

if (someCondition) {





Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container> satisfies a similar need in Angular templates.


We use ngNonBindable when we want tell Angular not to compile, or bind, a particular section of our page.

The most common example of this is if we wanted to write out some Angular code on the page, for example if we wanted to render out the text {{ name }} on our page, like so:


To render the name variable we use this syntax <pre>{{ name }}</pre>


Normally Angular will try to find a variable called name on the component and print out the value of the name variable instead of just printing out {{ name }}. To make angular ignore an element we simply add the ngNonBindable directive to the element, like so:


To render the name variable we use this syntax <pre ngNonBindable>{{ name }}</pre>


The NgSwitch directives

NgSwitch is like the JavaScript switch statement. It can display one element from among several possible elements, based on a switch condition. Angular puts only the selected element into the DOM. NgSwitch is actually a set of three, cooperating directives: NgSwitch, NgSwitchCase, and NgSwitchDefault as seen in this example.


<div [ngSwitch]=”currentHero.emotion”>

<happy-hero    *ngSwitchCase=”‘happy'”    [hero]=”currentHero”></happy-hero>

<sad-hero      *ngSwitchCase=”‘sad'”      [hero]=”currentHero”></sad-hero>

<confused-hero *ngSwitchCase=”‘confused'” [hero]=”currentHero”></confused-hero>

<unknown-hero  *ngSwitchDefault           [hero]=”currentHero”></unknown-hero>


NgSwitch is the controller directive. Bind it to an expression that returns the switch value. The emotion value in this example is a string, but the switch value can be of any type.


Bind to [ngSwitch]. You’ll get an error if you try to set *ngSwitch because NgSwitch is an attribute directive, not a structural directive. It changes the behavior of its companion directives. It doesn’t touch the DOM directly.

Bind to *ngSwitchCase and *ngSwitchDefault. The NgSwitchCase and NgSwitchDefault directives are structural directives because they add or remove elements from the DOM.

  • NgSwitchCase adds its element to the DOM when its bound value equals the switch value.
  • NgSwitchDefault adds its element to the DOM when there is no selected NgSwitchCase.

The switch directives are particularly useful for adding and removing component elements. This example switches among four “emotional hero” components defined in the hero-switch.components.ts file. Each component has a hero input property which is bound to the currentHero of the parent component.

Switch directives work as well with native elements and web components too. For example, you could replace the <confused-hero> switch case with the following in src/app/app.component.html

<div *ngSwitchCase=”‘confused'”>Are you as confused as {{currentHero.name}}?</div>

Go back to Tutorial

Get industry recognized certification – Contact us