typescript 从模板以角度 2 创建循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35472511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:17:33  来源:igfitidea点击:

create loop for, in angular 2 from a template

typescriptangular

提问by Angel Angel

Is possible, use something like the following in a template of angular2,

有可能,在angular2的模板中使用类似以下的内容,

for int a = 0; a < numberTest; a++

this numberTest is in code component:

这个 numberTest 在代码组件中:

numberTest: number = 5;

and the template, something like this, it is better to illustrate what I mean:

和模板,像这样的东西,最好说明我的意思:

<li *ngFor="#int a = 0; a < numberTest">


I know that could be solved using an array, and iterate for example:

我知道可以使用数组来解决,例如迭代:

<li *ngFor="#item of items">

but my question is, if possible, create a for, in the template, which take the value condition using a variable component, hope I explain well.

但我的问题是,如果可能的话,在模板中创建一个 for, ,它使用变量组件取值条件,希望我能解释清楚。

采纳答案by Sasxa

Maybe something like this:

也许是这样的:

<li *ngFor="#int of range(numberTest)">

with a helper function:

带有辅助功能:

let range = (value) => { 
 let a = []; for(let i = 0; i < value; ++i) { a.push(i+1) } return a; }

http://plnkr.co/edit/CNVqxU?p=preview

http://plnkr.co/edit/CNVqxU?p=preview

回答by Evan Plaice

NgFor includes an indexvalue for exactly this purpose

NgFor 包含了一个index正是为了这个目的的值

No function or intermediate state necessary.

不需要函数或中间状态。

<ul *ngFor="#item of items; #i = index">
  <li *ngIf="i < numberTest">{{ item }}</li>
</ul>

Source: Angualar2 Docs - NgFor

资料来源:Angualar2 文档 - NgFor

Note: This isn't tested so it may require a little tweaking.

注意:这未经过测试,因此可能需要稍作调整。