3 回答

TA貢獻1757條經(jīng)驗 獲得超8個贊
在組件內(nèi),您可以定義一個數(shù)字數(shù)組(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]
}
}
請參閱此鏈接以獲取數(shù)組創(chuàng)建:在JavaScript中從1..20創(chuàng)建整數(shù)數(shù)組的最有趣的方法。
然后可以使用以下方法遍歷此數(shù)組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條經(jīng)驗 獲得超3個贊
您與“非優(yōu)雅”解決方案非常接近。
怎么樣:
<div class="month" *ngFor="let item of [].constructor(10); let i = index">
...
</div>
在這里,我Array從一個空數(shù)組獲取構(gòu)造函數(shù):[].constructor,因為Array在模板語法中它不是公認的符號,而且我也懶得去做,Array=Array或者counter = Array像@ pardeep-jain在他的第四個示例中那樣在組件打字稿中也懶得做。我new之所以這么稱呼它,是因為new不需要從Array構(gòu)造函數(shù)中獲取數(shù)組。
Array(30)和new Array(30)等價。
該數(shù)組將為空,但這沒關(guān)系,因為您真的只想在循環(huán)中使用ifrom ;let i = index。
- 3 回答
- 0 關(guān)注
- 2006 瀏覽
添加回答
舉報