Structural directives shorthand syntax

Have you ever wondered what’s behind the following syntax?

Whenever I teach Angular, people end up asking me: “Why is there a * before ngIf and ngFor? If I don’t use the *, the IDE seems to be OK with it.”

Well, yes and no. If you wanted to remove the *, then you would have to write:

In other words, *ngIf is a shorthand syntax for <ng-template [ngIf]>. It’s designed to make our template syntax more manageable and easier to read.

This is especially true if you use local variables from exported directive values. In those scenarios, the “long” syntax is barely readable with the let- declarations:

Note that this syntax trick applies to all directives if you prefix them with *. Here is an example where I created my own structural directive to select tab templates.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.