NgSwitch class

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">
  <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]', visibility: Visibility.all)

Constructors

NgSwitch()

Properties

hashCode int
The hash code for this object.
no setterinherited
ngSwitch ← dynamic
no getter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited