【Angualr】ngForで配列などの要素を表示する

本記事では、フレームワークAngularで用いられるngForディレクティブについて紹介します。

ディレクティブという難しい言葉が出てきましたが、要は、ngForというものは、

HTMLで配列などの要素を動的に表示することができるものです。

次に実際にコードを見て、どのようにngForディレクティブを扱うか見ていきましょう。

本記事のAngularのバージョン

バージョン Angular CLI: 16.1.5

準備

コンポーネント生成

Angularのワークスペースで新しくコンポーネントを用意します。

$ ng g c ngfor

ngforは、好みのコンポーネント名に変えていただいてよいです。

生成したコンポーネントに配列を定義し、その要素をテーブルとして表示させましょう。

ngfor.component.ts

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

@Component({
  selector: 'app-ngfor',
  templateUrl: './ngfor.component.html',
  styleUrls: ['./ngfor.component.css']
})
export class NgforComponent {
  names = ["sato","suzuki","takahashi","tanaka","ito"];
}

app.component.html

<app-ngfor></app-ngfor>

例1:配列を表示

ngForディレクティブの書き方は以下の通り。

<div *ngFor='let element of 配列名'>{{ element }}</div>

let element of 配列名 は、JavaScriptの配列の要素を取り出す繰り返し文ですね。

配列から取り出した要素elementを{{}}の中に記述することで要素を表示させることができます。

elementは、他の名前にして頂いても問題ありません。

ngfor.component.html

<table border="1">
    <tr>
        <td>全国で多い名前</td>
    </tr>
    <tr *ngFor="let element of names">
        <td>{{ element }}</td>
    </tr>
</table>

ブラウザで確認すると。。。

例2:連想配列の表示

連想配列の表示は、以下のように記述することで表示できます。

ngfor.component.ts

// 省略
export class NgforComponent {
    prices = {
    "meat": 160,
    "fish": 100,
    "cheese": 77,
  };
}

ngfor.component.html

<table border="1">
    <caption>料金表</caption>
    <tr *ngFor="let element of prices | keyvalue">
        <th>{{ element.key }}</th>
        <td>{{ element.value }}</td>
    </tr>
</table>

ブラウザで確認すると。。。

例3:オブジェクト配列の表示

オブジェクトの配列は以下のように記述することで表示できます。

ngfor.component.ts

// 省略
export class NgforComponent {
population =[
    {
      name: 'Japan',
      population: 130000000
    },
    {
      name: 'China',
      population: 1448500000
    },
    {
      name: 'USA',
      population: 340000000
    }
  ];
}

ngfor.component.html

<table border="1">
    <caption>国の人口</caption>
    <tr *ngFor="let element of population">
        <th>{{ element.name }}</th>
        <td>{{ element.population }}</td>
    </tr>
</table>

ブラウザで確認すると。。。

まとめ

ngForディレクティブを用いて、配列、連想配列、オブジェクトの配列の表示方法を紹介しました。

このようにngForディレクティブは、配列のようなデータを繰り返し処理で表示させることができるのです。