notebook

都内でWEB系エンジニアやってます。

条件によってテンプレートを使い分ける

よくあるパターンで何らかの条件によって別のテンプレートを読み込みたい、みたいな時

ngSwitchを使うことで条件によって表示やテンプレートを出し分ける、みたいなことができるようです

ngSwitchで判定する値を指定

ngSwitchCaseで値ごとにタグを指定

ngSwitchDefaultでデフォルトのタグを指定

といった記述をすることで自動で切り替えてくれます

  • switch.component.html
<button (click)="key='foo'" class="btn btn-primary">Foo</button>
<button (click)="key='bar'" class="btn btn-success">Bar</button>

<ng-container [ngSwitch]="key">
  <app-foo *ngSwitchCase="'foo'" [params]="fooParams">
  </app-foo>
  <app-bar *ngSwitchCase="'bar'" [params]="barParams">
  </app-bar>
  <ng-container *ngSwitchDefault>
    <div>not Selected</div>
  </ng-container>
</ng-container>
  • switch.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-switch',
  templateUrl: './switch.component.html',
  styleUrls: ['./switch.component.scss']
})
export class SwitchComponent implements OnInit {

  constructor() { }

  private fooParams: any = [
    {name: "bob", age: 20},
    {name: "joe", age: 30},
    {name: "mike", age: 25},
  ];

  private barParams: any = [
    {name: "ryan", age: 40, bloodType: "A"},
    {name: "john", age: 36, bloodType: "B"},
  ];

  ngOnInit() {
  }
}
  • foo.component.ts
import {Component, OnInit, Input} from '@angular/core';

@Component({
  selector: 'app-foo',
  templateUrl: './foo.component.html',
  styleUrls: ['./foo.component.scss']
})
export class FooComponent implements OnInit {

  constructor() { }
  @Input() params: any;

  ngOnInit() {
  }
}
  • foo.component.html
<div>Fooのレンプレート</div>
<div class="container">
  <table class="table table-striped">
    <thead>
      <tr>
        <th>名前</th>
        <th>年齢</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let row of params">
        <td>{{row.name}}</td>
        <td>{{row.age}}</td>
      </tr>
    </tbody>
  </table>
</div>

例ではkeyの値によって表示するコンポーネントを変えています

fooの場合はapp-fooコンポーネント,barの場合はapp-barコンポーネントがそれぞれ呼ばれるようになっています

呼び出される子コンポーネント側は@Inputでデータを受け取っています

サンプルをgithub-pageにあげました

ng2-smple/switch

https://swfz.github.io/ng2-sample/switchswfz.github.io

ソースはこちら

ng2-sample/src/app/components/switch at master · swfz/ng2-sample

github.com

関係ないですがangular-cligithub-pageにも簡単に上げることができるのでとても楽チンですね