Structural Directives in Angular

What are 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.

Three of the common, built-in structural directives;

  • NgIf
  • NgFor
  • NgSwitch

What is ngIf directive?

This directive takes a Boolean expression and makes an entire chunk of the DOM appear or disappear.

<p *ngIf="true">
  Expression is true and ngIf is true. This paragraph is in the DOM.
</p>
<p *ngIf="false">
  Expression is false and ngIf is false. This paragraph is not in the DOM.
</p>

What is ngFor directive?

The NgFor directive is a way of repeating a template by using each item of an iterable as that template’s context.

<div *ngFor="let number of [10,20,30]; let i=index;">
  index: {{i}}, value: {{number}}
</div>
<!-- outputs
<div>index: 0, value: 10</div>
<div>index: 1, value: 20</div>
<div>index: 2, value: 30</div>
-->

NgFor also provides other values that can be aliased to local variables:

  • index – position of the current item in the iterable starting at 0
  • first – true if the current item is the first item in the iterable
  • last – true if the current item is the last item in the iterable
  • even – true if the current index is an even number
  • odd – true if the current index is an odd number

What is ngSwitch directive?

The Angular NgSwitch is actually a set of cooperating directives: NgSwitch, NgSwitchCase, and NgSwitchDefault.

NgSwitch itself is not a structural directive. It’s an attribute directive that controls the behaviour of the other two switch directives. NgSwitchCase and NgSwitchDefault are structural directives. An NgSwitchCase displays its host element when its value matches the switch value. The NgSwitchDefault displays its host element when no sibling NgSwitchCase matches the switch value.