3 回答

TA貢獻1757條經驗 獲得超8個贊
在組件內,您可以定義一個數字數組(ES6),如下所述:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill().map((x,i)=>i); // [0,1,2,3,4]
this.numbers = Array(5).fill(4); // [4,4,4,4,4]
}
}
請參閱此鏈接以獲取數組創建:在JavaScript中從1..20創建整數數組的最有趣的方法。
然后可以使用以下方法遍歷此數組ngFor:
@Component({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
或不久:
@Component({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}

TA貢獻1773條經驗 獲得超3個贊
您與“非優雅”解決方案非常接近。
怎么樣:
<div class="month" *ngFor="let item of [].constructor(10); let i = index">
...
</div>
在這里,我Array從一個空數組獲取構造函數:[].constructor,因為Array在模板語法中它不是公認的符號,而且我也懶得去做,Array=Array或者counter = Array像@ pardeep-jain在他的第四個示例中那樣在組件打字稿中也懶得做。我new之所以這么稱呼它,是因為new不需要從Array構造函數中獲取數組。
Array(30)和new Array(30)等價。
該數組將為空,但這沒關系,因為您真的只想在循環中使用ifrom ;let i = index。
- 3 回答
- 0 關注
- 2007 瀏覽
添加回答
舉報