ngSwitch with Angular 2 and TypeScript

The ngSwitch directive displays one element (and its children) from a set of possible options, based on some condition.

Updated Nov 2017, Angular version 5.0

Example

ngSwitch is bound to the choice variable, and only the <h3> element with the ngSwitchCase which matches the value of choice is displayed. If no ngSwitchCase is matched then ngSwitchDefault is used instead.

ng-switch.component.ts
import { Component } from '@angular/core';

@Component({
    template: `
        <h2>ngSwitch</h2>

        <select #select [(ngModel)]="choice">
            <option value="one">one</option>
            <option value="two">two</option>
            <option value="three">three</option>
            <option value="another">another</option>
        </select>

<div [ngSwitch]="choice"> <h3 *ngSwitchCase="'one'">First</h3> <h3 *ngSwitchCase="'two'">Second</h3> <h3 *ngSwitchCase="'three'">Third</h3> <h3 *ngSwitchDefault>Default</h3> </div>`
}) export class NgSwitchComponent { public choice = 'one'; }

The Application

You can see this in action here.

Where Next?

To find out more about Angular and TypeScript, check out these tutorials.

  • Hello World - Implement a super-simple <hello-world> custom element using an Angular and TypeScript.
  • The Angular with TypeScript Tutorial - includes examples of components, template syntax, property binding, event binding, bootstrapping and more.
  • Configuration - Configure Angular and TypeScript to download dependencies from node modules or a CDN, and to compile the TypeScript during development or in the browser at runtime.
  • Templates - introduction to inline and external templates.
  • Interpolation - use curly braces and template expressions to output data on the page.
  • Property Binding - bind to DOM properties using square brackets and template expressions.
  • Event Binding - handle DOM events using parentheses and template statements.
  • Two-way Binding - combine property and event binding to create two-way binding with ngModel.
  • Input Binding - bind to <input> fields such as text, textarea, checkbox, radio and select.
  • Built-in Directives - see how to use built-in directives ngIf, ngSwitch, ngFor, ngClass and ngStyle.
  • Component Input Output - use @Input and @Output to pass data in to and out of a component.
  • Angular Router - Use the Angular router to navigate between components when the user clicks a link.
  • Nested Child Routes - An example of how child routes allow navigation between multiple views when a user clicks a link in a sub-menu.