本文介绍了角度2:如何编写for循环,而不是foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:30