Angular ngFor ディレクティブによる繰り返し処理

📋 目次(クリックで展開)

Angular の ngFor ディレクティブを利用することで、HTML テンプレート上で繰り返し処理を行うことができます。

実装内容

app.component.ts

簡単な例として、items という文字列配列があるとします。

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'build-test';
items = [];
ngOnInit() {
for (let i = 0; i < 10; i++) {
this.items.push(`item ${i}`);
}
}
}

app.component.html

HTML テンプレート上で、ngFor で items 配列のすべての要素を出力します。ngFor ディレクティブを div などの HTML 要素上で使う際には、*(アスタリスク)を付けます。

<div *ngFor="let item of items">
{{ item }}
</div>

出力結果は次のとおりです。


💬 コメント