Angular, Directive *ngSwitch


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 https://hub.docker.com/r/szalek/angular-cli/

Create new component

ng g c switcher

Output

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)

switcher.component.ts

import { Component } from '@angular/core';
 
@Component({
 selector: 'app-switcher',
 templateUrl: './switcher.component.html'
})
export class SwitcherComponent {
 king:String = ''
}

switcher.component.html

<section>

  <button (click)="king = '1'">1</button>
  <button (click)="king = '2'">2</button>
  <button (click)="king = '3'">3</button>
  <button (click)="king = '4'">4</button>
  <button (click)="king = '5'">5</button>

  <div [ngSwitch]="king">

    <div *ngSwitchCase="'1'">Mieszko I of Poland</div>
    <div *ngSwitchCase="'2'">Bolesław I the Brave</div>
    <div *ngSwitchCase="'3'">Mieszko II Lambert</div>
    <div *ngSwitchCase="'4'">Bezprym</div>
    <div *ngSwitchCase="'5'">Otto Bolesławowic</div>

    <div *ngSwitchDefault>no king :(</div>

  </div>

</section>

Usage

<app-switcher></app-switcher>