What are Structural Directives in Angular?

Structural Directives in Angular modify what is displayed in a view. They live directly in the HTML. They modify our HTML by adding, removing, or manipulating elements.

Why are they called structural directives? It is because they modify the structure of the Document Object Model (DOM).

Structural directives are easy to spot. They will begin with an asterisk (*). And the two most common structural directives are *ngIf and *ngFor.

Above is how we use a *ngIf. The if statement will evaluate on TheTomBomb and only if that is true will it include “Thomas is the best” into our DOM and viewable to the user.

If TheTomBomb evaluates to false “Thomas is the best” will not display. And not only that, but it will also not be present in the DOM.

The above *ngFor will print out a list of website url’s. The websites variable is a list of websites and we will loop of that and generate a new <li> for each one in our collection. So a new <li> element will be created in the DOM for each item in websites.

Structural directives are popular and give us added capabilities inside of our HTML. *ngIf is perfect for showing and hiding data. *ngFor is great when we need to generate repeated HTML.

To learn more check out the Angular documentation on Structural Directives.

Author: TheTomBomb

A mob programmer, mobile developer, backpacking, explorer

Published by

TheTomBomb

A mob programmer, mobile developer, backpacking, explorer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.