Angular
Fundamentals of Angular Directives - Structural Directives
  •  

Built-in Structural Directives

PRO
Outline

Angular's Three Built-in Structural Directives

Angular ships with three very powerful structural directives:

  1. NgIf
  2. NgForOf
  3. NgSwitch

NgIf Structural Directive

The NgIf structural directive is similar to the if-statement in most (if not all) programming languages that is provided with an expression that is evaluated to be either true or false. When the expression is true the host element and it's content is created in the document at the position of the host element. When false, the host element and it's content is removed.

One thing to keep in mind is that if the host element or any of it's child elements contain directives, those directives and event listeners are also created. Likewise, when the host element and any of it's child elements are destroyed, those directives and any associated event listeners are also removed.

Finally, note that the class name is NgIf while the directive's selector value is [ngIf] (an attribute selector that matches "ngIf").

NgForOf Structural Directive

The NgFor structural directive is similar to a for-loop in most programming languages; in that it receives an iterable and then iterates (or loops) over each item in the collection. An iterable is most often an Array, but it can also be other iterable objects in ECMAScript, such as Int8Array or a Generator.

Note that the class name is NgForOf while the directive's selector is [ngFor].

NgSwitch Structural Directive

The NgSwitch structural directive is similar to a switch-statement in most programming languages. This directive enables us to conditionally output one, or more, host elements determined by the value of an expression specified to the directive. As we'll learn, this directive works well with enumerations in TypeScript.

Note that the class name is NgSwitch while the directive's selector is [ngSwitch].

 

I finished! On to the next chapter