君は心理学者なのか?

大学時代に心理学を専攻しなぜかプログラマになった、サイコ(心理学)プログラマかろてんの雑記。

Angular2/4にてngSwitchを使ってtemplateの一部切り替えを行う

Angular2/4にてngSwitchを使ってtemplateの切り替えを行う

「routerを使う程ではないけど、templateを部分的に書き換えたいな〜」と思ったので、

ngSwitchを使用してtemplateの部分的な切り替えを行おうと思います。

0. 準備

新規プロジェクトを作成し、サーバをスタートさせます。

ng new ng-switch
ng serve

1. app.component.htmlの修正

<!-- app.component.html -->
<button (click)="onClick()">おしてね</button>
<div [ngSwitch]="templateFlg"> <!-- 重要 -->
  <div *ngSwitchCase="true"> <!-- 重要 -->
    <img style="display: inline;"
        src="https://pbs.twimg.com/profile_images/442329275769683968/gvLogHdH.jpeg"
        width="250px"
        height="250px"
        >
    <div style="display: inline;">(・(ェ)・)</div>
  </div>
  <div *ngSwitchCase="false">  <!-- 重要 -->
    <img style="display: inline;"
         src="https://pbs.twimg.com/profile_images/795060602309726208/WAKx1L5U.jpg"
         width="250px"
         height="250px"
         >
    <div style="display: inline;">(ΘェΘ)</div>
  </div>
</div>

templateの解説

<div [ngSwitch]="templateFlg">
  <div *ngSwitchCase="true">
    <!-- templateFlg == true の場合に表示されるtemplate -->
  </div>
  <div *ngSwitchCase="false">
    <!-- templateFlg == false の場合に表示されるtemplate -->
  </div>
</div>

ngSwitchには、出し分けするために用意した変数を代入します。

今回の場合はtemplateFlgという変数を用います。

それぞれのtemplateには*ngSwitchCaseを使って、

どの条件のときにtemplateを表示するかを記載します。

2. AppComponentの修正

import { Component } from '@angular/core';
import { NgSwitch } from '@angular/common'; // 追記

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  /** ここから */
  private templateFlg = true;
  onClick()
  {
    this.templateFlg = !this.templateFlg;
  }
  /** ここまで追記 */
}

結果

f:id:karoten512:20171004160035g:plain