Tambourine作業メモ

主にスキル習得のためにやった作業のメモ。他人には基本的に無用のものです。

Angularで遊ぶ(7) - ディレクティブ - ngFor

お仕事だと一番よく使うかもしれない、要素をテーブルにするための繰り返しのディテクティブ。

TABLEなら繰り返しの指示は<table>に書く。 複数の要素を繰り返したかったら<ng-container>というダミーの枠を作る。

app.component.html

<table class="table">
  <tr>
    <th>No</th><th>通称</th><th>型式番号</th><th>主なパイロット</th>
  </tr>
  <tr *ngFor="let b of ms; index as i">
    <td>{{i + 1}}</td>
    <td>{{b.name}}</td>
    <td>{{b.no}}</td>
    <td>{{b.pilot}}</td>
  </tr>
</table>

<hr />

<ng-container *ngFor="let b of ms; odd as o">
  <h5>{{b.no}}</h5>
  <p [style.background-color]="o ? 'blue' : 'gray'">{{b.name}}</p>
</ng-container>

app.component.ts

export class AppComponent {
  ms = [
    {
      name: "ガンダム",
      no: "RX-78",
      pilot: "アムロ・レイ",
    },
    {
      name: "Ζガンダム",
      no: "MSZ-006",
      pilot: "カミーユ・ビダン",
    },
    {
      name: "百式",
      no: "MSN-001",
      pilot: "クワトロ・バジーナ",
    },
    {
      name: "ΖΖガンダム",
      no: "MSZ-010",
      pilot: "ジュドー・アーシタ",
    },
  ]
}

インデックスや奇数列・偶数列が簡単にとれるのは良いね

f:id:Tambourine:20180924125434p:plain