Structural Directives

Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure, typically by adding, removing, or manipulating elements.

As with other directives, you apply a structural directive to a host element. The directive then does whatever it's supposed to do with that host element and its descendants.

Structural directives are easy to recognize. An asterisk (*) precedes the directive attribute name as in this example.

What are structural directives?

  • Manipulate a components template

    • Can hide or remove components and elements

    • Iterate over arrays and execute a portion of the template for each instance

    • Examples

      • ngFor

      • ngIf

      • ngSwitch

Structural Directive Examples

app.component.ts
<div *ngIf="show" class="name">{{product.name}}</div>

<ul>
  <li *ngFor="let product of products">{{product.name}}</li>
</ul>

<div [ngSwitch]="product?.type">
  <app-product-kitchen *ngSwitchCase="'kitchen'" [product]="product"></app-product-kitchen>
  <app-product-bath *ngSwitchCase="'bath'" [product]="product"></app-product-bath>
  <app-product-bedroom *ngSwitchCase="'bedroom'" [product]="product"></app-product-bedroom>
  <app-product-unknown *ngSwitchDefault [product]="product"></app-product-unknown>
</div>

The asterisk (*) notation is a convenience notation and the string part is a micro-syntax.

*ngIf Directive

Remove vs Hide

  • Component behavior continues even when hidden

  • Showing a hidden element is very fast

  • Prefer removal over hiding components

Asterisks Prefix

Angular translates the *ngIf directive into a <ng-template> element

ng-if2.html
<div *ngIf="show" class="name">{{product.name}}</div>

//translates *ngIf to an ng-template
<ng-template [ng-if]="show">
    <div class="name">{{product.name}}</div>
</ng-tempolate>

*ngFor Directive

*ngFor enumerates over an array and returns each individual item. The outer element is repeated for each item returned.

  • Acccess variables like index and odd for special formatting

  • trackBy function can improve performance for insertion and deletion

    • trackById(index, item) { return item.id }

    • Helps Angular find items faster by using the unique id

ngSwitch Directive

Is a set of co-operative directives: `ngSwitch, ngSwitchCase, ngSwitchDefault`. The value assigned to ngSwitch determines which switch cases are displayed. ngSwitch is actually an attribute directive and controls the behavior of the other two structural directives.

Create Custom Structural Directive

We will create a custom structural directive UnlessDirective that is opposite of the ngIf directive. It will show it's content if it's condition is false.

Let's create a new directive using ng g d unless to generate the directive.

Summary

  • Structural directives including *ngIf, *ngFor, and ngSwitch

  • The asterisk prefix

  • How ng-template is used

  • How to create a custom strucural directive

Last updated