The Syntax of Structural Directives

Learn the structural directive syntax.

Let’s get deep into the theory behind structural directives so that we can understand how they really work. Structural directives are more complicated than attribute directives because they need to manipulate the DOM. Also, we operate the DOM through the Angular API which, at the start, is not as simple to understand as ordinary DOM manipulation. However, if we stick with it, we’ll find that it is not too difficult with a little practice. Let’s go through the syntax of structural directives now so that we can implement our own.

Why we use the * syntax?

Usually, when we apply structural directives like NgIf or NgFor, we use the asterisk (*) symbol.

For example, this is how we use NgIf:

<div *ngIf="true"> Hello there! </div> 

Why do we use the asterisk? Because it marks that directive as structural in Angular. We need to do that for a very good reason. Let’s imagine what would happen if we omitted the asterisk:

<div ngIf="true"> Hello there! </div> 

Without the asterisk, Angular treats NgIf as an attribute directive and, more importantly, the rendered

element is added to the DOM! We don’t want this to happen. So, we want to have control over this.

We need Angular to treat this element not as a regular element, but as a template that we can then use to add to or remove from the DOM.

Get hands-on with 1200+ tech skills courses.