Adds or removes DOM sub-trees when their match expressions match the switch expression.

Elements within NgSwitch but without NgSwitchWhen or NgSwitchDefault directives will be preserved at the location as specified in the template.

NgSwitch simply inserts nested elements based on which match expression matches the value obtained from the evaluated switch expression. In other words, you define a container element (where you place the directive with a switch expression on the [ngSwitch]="..." property), define any inner elements inside of the directive and place a [ngSwitchWhen] property per element.

NgSwitchWhen is used to inform NgSwitch which element to display when the expression is evaluated. If a matching expression is not found via ngSwitchWhen then an element with an NgSwitchDefault is displayed.

Examples

<div [ngSwitch]="hero?.emotion">
  <happy-hero    *ngSwitchCase="'happy'"    [hero]="hero"></happy-hero>
  <sad-hero      *ngSwitchCase="'sad'"      [hero]="hero"></sad-hero>
  <confused-hero *ngSwitchCase="'confused'" [hero]="hero"></confused-hero>
  <unknown-hero  *ngSwitchDefault           [hero]="hero"></unknown-hero>
</div>
<div [ngSwitch]="hero?.emotion">
  <happy-hero    template="ngSwitchCase 'happy'"    [hero]="hero"></happy-hero>
  <sad-hero      template="ngSwitchCase 'sad'"      [hero]="hero"></sad-hero>
  <confused-hero template="ngSwitchCase 'confused'" [hero]="hero"></confused-hero>
  <unknown-hero  template="ngSwitchDefault"         [hero]="hero"></unknown-hero>
</div>
<div [ngSwitch]="hero?.emotion">
  <template [ngSwitchCase]="'happy'">
    <happy-hero [hero]="hero"></happy-hero>
  </template>
  <template [ngSwitchCase]="'sad'">
    <sad-hero [hero]="hero"></sad-hero>
  </template>
  <template [ngSwitchCase]="'confused'">
    <confused-hero [hero]="hero"></confused-hero>
  </template >
  <template ngSwitchDefault>
    <unknown-hero [hero]="hero"></unknown-hero>
  </template>
</div>

Try the live example. For details, see the Structural Directives section on ngSwitch.

Annotations
  • @Directive(selector: '[ngSwitch]', inputs: const ['ngSwitch'])

Constructors

NgSwitch()

Properties

ngSwitch value
write-only
hashCode → int
The hash code for this object. [...]
read-only, inherited
runtimeType → Type
A representation of the runtime type of the object.
read-only, inherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a non-existent method or property is accessed. [...]
inherited
toString() → String
Returns a string representation of this object.
inherited

Operators

operator ==(other) → bool
The equality operator. [...]
inherited