FrontEndTech
  • Introduction
  • ReactJS
    • Ecosystem
    • Refactor Using Functional Decomposition and Reducer Composition
  • AngularJS
    • installation
    • File structure
    • CLI
      • ng g
    • Fundamentals
      • Component
        • Lifecycle
        • Template
      • Decorations
      • Service
      • Pipe
      • Directives
        • NgClass
        • NgStyle
        • NgModel
        • Customized Attribute Directives
        • NgIf
        • NgFor
        • NgSwitch
        • NgForm
        • Customized Structural Directives
      • Module
        • Routing
    • Bindings
      • Property Binding
      • Event Binding
      • Data Binding
      • Attribute Binding
      • Class Binding
      • Style Binding
    • Forms
      • Reactive Form
      • Reactive vs Template
    • build
Powered by GitBook
On this page

Was this helpful?

  1. AngularJS
  2. Fundamentals
  3. Directives

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.

PreviousNgForNextNgForm

Last updated 5 years ago

Was this helpful?