Angular

Fundamentals of Angular Directives - Structural Directives

PRO

Introduction to Structural Directives

While attribute directives in Angular enable us to specify an attribute on an element in our templates to enhance, to change the behavior, or to alter the display of the element, structural directives enable us to efficiently create, remove and alter existing elements in the Document Object Model (DOM).

Similar to attribute directives in that we will be applying the directive to a host element in the DOM. Unlike attribute directives, we can only apply one structural directive the host element.

Microsyntax

Structural Directives have a "full" syntax, which is a little cumbersome to use, as well as a much more convenient and easier to use microsyntax. Throughout the course, we'll be using the microsyntax.

Benefits and Costs

Structural directives have both benefits and costs related to the creation and destruction of elements in the DOM.

Creating elements, along with the necessary event listeners, can be expensive. Don't get too caught up in this - it's just good to know that if you start to create thousands, hundreds of thousands, and perhaps even, millions of elements in the DOM it does have a cost and your users could notice a perceived slowness to your application.

Destroying, and removing any event listeners that were applied, is a good thing; allowing the JavaScript engine's garbage collection to free up memory in our application.

Built-in Angular Structural Directives

Angular has three built-in, and very powerful, structural directives:

  1. NgIf
  2. NgFor
  3. NgSwitch

We'll be covering these structural directives in detail.

Microsyntax

As mentioned, we'll be using the convenient microsyntax. Here is an example of the NgIf microsyntax:

<div *ngIf="loading">
  <spinner></spinner>
</div>

At the moment, take note of the asterisk ( * ) that is used in the syntax, which is preceeding the NgIf directive.

The full syntax that is applied to the DOM is:

<ng-template [ngIf]="loading">
  <div>
    <spinner></spinner>
  </div>
</ng-template>

The ng-template custom element is never rendered to the DOM, rather, it serves to create a ViewContainerRef instance, which is the view container into which we will render the contents of the ng-template element. The ng-template element is the host element for the NgIf structural directive. Note the square brackets around the directive's selector, which in this case is ngIf. To clarify, the class name is NgIf and the directive's selector value is ngIf.