Skip to content

Angular, Directive *ngSwitch

2017-11-13 03:00:44

Simple example of ngSwitch directive that is part of Angular core. Everything what you need will be generated after executing this command ng g c switcher. After that, what you have to do, is adjust few files. Of course more you can find in Angular documentation, here we have only my notes. One more thing, if you don't like to install node mess on your local computer you can use my or similar docker image

Create new component

ng g c switcher


create src/app/switcher/switcher.component.css (0 bytes)
create src/app/switcher/switcher.component.html (27 bytes)
create src/app/switcher/switcher.component.spec.ts (642 bytes)
create src/app/switcher/switcher.component.ts (337 bytes)
update src/app/app.module.ts (1355 bytes)


import { Component } from '@angular/core';

 selector: 'app-switcher',
 templateUrl: './switcher.component.html'
export class SwitcherComponent {
 king:String = ''


<button '1'&quot;="" (click)='"king' =="">1</button>
<button '2'&quot;="" (click)='"king' =="">2</button>
<button '3'&quot;="" (click)='"king' =="">3</button>
<button '4'&quot;="" (click)='"king' =="">4</button>
<button '5'&quot;="" (click)='"king' =="">5</button>
<div [ngswitch]='"king"'>
<div *ngswitchcase="&quot;'1'&quot;">Mieszko I of Poland</div>
<div *ngswitchcase="&quot;'2'&quot;">Bolesław I the Brave</div>
<div *ngswitchcase="&quot;'3'&quot;">Mieszko II Lambert</div>
<div *ngswitchcase="&quot;'4'&quot;">Bezprym</div>
<div *ngswitchcase="&quot;'5'&quot;">Otto Bolesławowic</div>
<div *ngswitchdefault="">no king :(</div>