NgSwitch, NgSwitchCase and NgSwitchDefault - directives in angular


The NgSwitch directive is actually a set of several directives: NgSwitch, NgSwitchCase, NgSwitchDefault. It is comprised of an attribute directive NgSwitch as well as the structural directive NgSwitchCase and NgSwitchDefault. 
  • NgSwitch is a directive that adds or remove the templates from the DOM when the next match expression matches the NgSwitch expression.
  • It behaves like a switch statement in javascript.
  • The expressions to match is provided by NgSwitchCase. 
  • Every view that matches the switch expression will be rendered in the DOM.
  • If no view is matched with NgSwitchCase then view with NgSwitchDefault will be rendered.
  • Elements inside NgSwitch but outside NgSwitchCase and NgSwitchDefault are preserved at their location. NgSwitchDefault is the last statement in NgSwitch.
  • NgSwitch is an attribute directive. It controls the behavior of the other two structural directives. That's why we write it as [ngSwitch] instead of *ngSwitch.
  • *NgSwitchCase displays its host element when its value is matched with the expression in NgSwitch.
General Syntax for NgSwitch
<root-container [ngSwitch]="expression">
  <element *ngSwitchCase="expression 1">...</element>
  <element *ngSwitchCase="expression 2">...</element>
  <element *ngSwitchCase="expression 3">...</element>
  <element *ngSwitchCase="expression 4">...</element>
  <element *ngSwitchDefault>...</element>

In the below example, the ngSwitch acts as a property binding. The direction is a property assigned to it. So on the basis of the value of direction, template view will be rendered.

<div [ngSwitch]="direction">
  <i *ngSwitchCase="East">East Direction</i>
  <i *ngSwitchCase="West">West Direction</i>
  <i *ngSwitchCase="North">North Direction</i>
  <i *ngSwitchCase="South">South Direction</i>
  <i *ngSwitchDefault>No Direction</i>
If value of direction is North, then  <i *ngSwitchCase="North">North Direction</i> will run.