NgSwitch

The Angular NgSwitch is actually a set of cooperating directives: NgSwitch, NgSwitchCase, and NgSwitchDefault.

src/app/app.component.html (ngswitch)

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

    • itself is not a structural directive.

    • It's an attribute directive that controls the behavior of the other two switch directives. That's why you write [ngSwitch], never *ngSwitch.

    • The emotion value in this example is a string, but the switch value can be of any type.

  • NgSwitchCase & NgSwitchDefault

    • structural directives.

    • You attach them to elements using the asterisk (*) prefix notation.

    • An NgSwitchCase displays its host element when its value matches the switch value.

    • The NgSwitchDefault displays its host element when no sibling NgSwitchCase matches the switch value.

Last updated

Was this helpful?