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.

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

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular desugars it in two stages. First, it translates the *ngIf="..."into a template attribute, template="ngIf ...", like this.

<divtemplate="ngIf hero">{{hero.name}}</div>

Then it translates the template attribute into a template element, wrapped around the host element, like this.

<template [ngIf]="hero"><div>{{hero.name}}</div></template>

The *ngIf directive moved to the <template> element where it became a property binding,[ngIf].

The rest of the <div>, including its class attribute, moved inside the <template> element.

None of these forms are actually rendered. Only the finished product ends up in the DOM.

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

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 <template>. In this example, the [ngClass]="odd" stays on the <div>.