问题描述
使用Angular 2,我想多次复制模板中的一行.在对象上进行迭代很容易,*ngFor="#object of objects"
.但是,我想运行一个简单的for
循环,而不是一个foreach
循环.类似于(伪代码):
Using Angular 2, I want to duplicate a line in a template multiple times. Iterating over an object is easy, *ngFor="#object of objects"
. However, I want to run a simple for
loop, not a foreach
loop. Something like (pseudo-code):
{for i = 0; i < 5; i++}
<li>Something</li>
{endfor}
我该怎么做?
推荐答案
您可以动态生成一个数组,其中包含要渲染<li>Something</li>
的时间,然后对该集合进行ngFor
.您也可以使用当前元素的index
.
You could dynamically generate an array of however time you wanted to render <li>Something</li>
, and then do ngFor
over that collection. Also you could take use of index
of current element too.
标记
<ul>
<li *ngFor="let item of createRange(5); let currentElementIndex=index+1">
{{currentElementIndex}} Something
</li>
</ul>
代码
createRange(number){
var items: number[] = [];
for(var i = 1; i <= number; i++){
items.push(i);
}
return items;
}
在引擎盖下,这种*ngFor
语法不再适用于ng-template
版本.
Under the hood angular de-sugared this *ngFor
syntax to ng-template
version.
<ul>
<ng-template ngFor let-item [ngForOf]="createRange(5)" let-currentElementIndex="(index + 1)" [ngForTrackBy]="trackByFn">
{{currentElementIndex}} Something
</ng-template>
</ul>
这篇关于角度2:如何编写for循环,而不是foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!