ngFor
form1.component.ts:
import { Component } from '@angular/core';
// Defines example component and associated template
@Component({
selector: 'example',
template: `
<div *ngFor="let f of fruit"> {{f}} </div>
<select required>
<option *ngFor="let f of fruit" [value]="f"> {{f}} </option>
</select>
`
})
// Create a class for all functions, objects, and variables
export class ExampleComponent {
// Array of fruit to be iterated by *ngFor
fruit = ['Apples', 'Oranges', 'Bananas', 'Limes', 'Lemons'];
}
輸出:
<div>Apples</div>
<div>Oranges</div>
<div>Bananas</div>
<div>Limes</div>
<div>Lemons</div>
<select required>
<option value="Apples">Apples</option>
<option value="Oranges">Oranges</option>
<option value="Bananas">Bananas</option>
<option value="Limes">Limes</option>
<option value="Lemons">Lemons</option>
</select>
最簡單的形式,*ngFor 有兩個部分: let variableName of object/array
在 fruit = ['Apples', 'Oranges', 'Bananas', 'Limes', 'Lemons']; 的情況下,
蘋果,橘子等是陣列 fruit 中的值。
[value]="f" 將等於*ngFor 迭代過的每個當前 fruit(f)。
與 AngularJS 不同,Angular2 沒有繼續使用 ng-options 用於 <select> 和 ng-repeat 用於所有其他一般重複。
*ngFor 與 ng-repeat 非常相似,語法略有不同。
參考文獻:
Angular2 | 顯示資料
Angular2 | ngFor
Angular2 | 形式