ngSwitch with Angular 2 and TypeScript - Loading..
Style: Blog or IDE

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 Jan 2017, Angular version 2.4.x

Quick Tip

In the text below, when you see a word or phrase with this color, click on it to highlight the source code.

Also, take a look at the IDE style to see this tutorial in wide-screen mode. You can always switch back using the Style link at the top of the page.

Show me the IDE style


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 x

The Application

You can see this in action here.


Where Next?

More Directives

To learn more about the other built-in directives, take a look at these tutorials.

  • ngIf adds and removes elements in the DOM based on the results of an expression.
  • ngFor is a repeater directive which outputs a list of elements by iterating over an array.
  • ngClass adds and removes CSS classes on an element.
  • ngStyle sets CSS styles on an HTML element conditionally.