Angular
Fundamentals of Angular Directives - Structural Directives

NgSwitch Built-in Structural Directive

PRO

Create or remove templates determined by an expression value

NgSwitch

The NgSwitch structural directive creates and removes templates when each template's expression value matches the value of the expression specified to the directive. Let's look at an example:

<div [ngSwitch]="person.department">
  <span *ngSwitchCase="'Engineering'">Software Engineering</span>
  <span *ngSwitchCase="'Testing'"> QA</span>
  <span *ngSwitchCase="'Marketing'">Marketing and Sales</span>
</div>

In this example, the directive's class defines the person object:

export class AppComponent {
  person = {
      id: 1,
        name: 'Brian', 
        department: 'Engineering`
    }
}

There are two expressions that are evaluated:

  1. The expression that is specified to the NgSwitch directive, in this case person.department.
  2. And, the expressions that are specified to each NgSwitchCase directive, in this case we are hard coding string values (note the single quotes around each value). You can also specify an expression to each template that is evaluated, and when it matches the value of the expressions specified to the NgSwitch directive the template is rendered in place.