Angular 2:如何编写 for 循环,而不是 foreach 循环 [英] Angular 2: How to write a for loop, not a foreach loop

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

问题描述

使用 Angular 2,我想多次复制模板中的一行.迭代一个对象很容易,*ngFor="let 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="let 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}

我该怎么做?

推荐答案

如果将 int 传递给 Array 构造函数,然后通过 ngFor 对其进行迭代.

You can instantiate an empty array with a given number of entries if you pass an int to the Array constructor and then iterate over it via ngFor.

在您的组件代码中:

export class ForLoop {
  fakeArray = new Array(12);
}

在您的模板中:

<ul>
  <li *ngFor="let a of fakeArray; let index = index">Something {{ index }}</li>
</ul>

索引属性为您提供迭代次数.

The index properties give you the iteration number.

现场版

这篇关于Angular 2:如何编写 for 循环,而不是 foreach 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆