【AngularJS】*ngFor属性で配列の要素を順に取り出し

AngularJSにおけるlowercase、uppercaseパイプで大文字・小文字へ相互変換する方法をまとめました。

## 【*ngFor属性】配列の要素を順に取り出し

*ngFor属性を使うと、配列の要素を順に取り出すことができます。

書式

<element *ngFor="let item of list">
contents
</element>
パラメータ 概要
element 要素
item 仮変数
list 配列
contents 繰り返し出力するコンテンツ

配列listの先頭から順に要素を取り出されます。
そして、最後の要素を取り出すと、処理を終了します。<

■app/app.component.ts

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

// コンポーネントの構成情報を定義するデコレータ
@Component({
  // コンポーネントの適用先を表すセレクター式
  selector: 'app-root',

  // コンポーネントに適用するスタイルシート
  styleUrls: ['./app.component.css'],

  // コンポーネントに適用するテンプレート(外部ファイルから読み込み)
  templateUrl: './app.component.html',
})

export class AppComponent {
  sites = [
    {
      url: 'https://algorithm.joho.info',
      title:'アルゴリズム雑記',
      depre: '「アルゴリズム雑記」です。',
    },
    {
      url: 'https://www.google.co.jp',
      title:'Google検索',
      depre: '「Google検索」です。',
     }
  ];
}

■app/app.component.html

<table>
    <tr>
      <th>サイト</th><th>概要</th>
    </tr>
    <tr *ngFor="let site of sites">
      <td><a href="{{site.url}}">{{site.title}}</a></td>
      <td>{{site.depre}}</td>
    </tr>
</table>

■実行結果

## 【*ngFor属性】「index as i」で連番作成

「index as i」を付加することで、連番を追加することもできます。
■app/app.component.html

<table>
    <tr>
      <th>サイト</th><th>概要</th>
    </tr>
    <tr *ngFor="let site of sites; index as i">
      <td>{{i + 1}}</td>
      <td><a href="{{site.url}}">{{site.title}}</a></td>
      <td>{{site.depre}}</td>
    </tr>
</table>
参考文献・関連記事
参考 【AngularJS入門】基礎的な使い方まとめ
参考 【AngularJS入門】基礎とサンプル集
関連 【Ionic入門】Android・iPhoneアプリ開発編
Javascript
スポンサーリンク
西住工房

コメント