【问题标题】:How to repeat *ngFor a number of times equal to the value of a variable?如何重复 *ngFor 的次数等于变量的值?
【发布时间】:2017-10-24 16:22:35
【问题描述】:

我正在使用 Ionic 2 框架以及 Angular 2 和 Ts。

在我的 ts 文件中,我有一个变量,比如说“round”和一个对象“textblocks”

round:number;
textblocks=[{hello:'hi'},{hello:'there'},{hello:'john'},{hello:'doe'}];

'Round' 值在应用程序的生命周期内不断变化(0 到 3)。

然后在我的 html 文件中,我有一个列表:

<ul>
  <li>{{textblocks[round].hello}}</li>      
</ul>

我可以使用 ngFor 来显示与变量“round”中的数字一样多的“li”,每个都显示对应的 textblocks[round].hello 中的文本,使用视图时“round”增加?

round 为 1 时的示例

<ul>
  <li>{{textblocks[0].hello}}</li>   
  <li>{{textblocks[1].hello}}</li>      
</ul>

那是

  • 你好
  • 那里

round 为 3 时的示例

<ul>
  <li>{{textblocks[0].hello}}</li>   
  <li>{{textblocks[1].hello}}</li> 
  <li>{{textblocks[2].hello}}</li> 
  <li>{{textblocks[3].hello}}</li>       
</ul>
  • 你好
  • 那里
  • 约翰
  • 确实

【问题讨论】:

  • 不。我以前找到了那个答案,但它没有考虑到“变量”问题。它解释了如何重复一个元素固定的次数(答案比 trichetriche 这里提供的要复杂得多)

标签: cordova angular ionic-framework ngfor


【解决方案1】:

是的,你可以,就像这样

<ul>
    <span *ngFor="let tb of textblocks; let i = index;">
        <li *ngIf="i <= round">{{tb.hello}}</li>
    </span>
</ul>

您可以用&lt;template&gt;&lt;/template&gt; 替换跨度,但我不记得确切的语法,所以我使用了跨度

【讨论】:

  • 完美运行!我没有考虑一起使用 ngIf !非常感谢
  • 没问题,记得标记为已解决。顺便说一句,你不能在同一个标​​签中使用 ngIf 和 ngFor,小心
  • 是的,还有 4 分钟,我会的。在同一个标​​签中使用它们是什么意思?
  • 我的意思是你不能做&lt;li *ngFor="..."' *ngIf="..."&gt;&lt;/li&gt;,这就是我使用span的原因
  • 很高兴知道!谢谢!
【解决方案2】:

您也可以使用 slice 管道,它是一个内置的 Angular 管道:

<li *ngFor="let textblock of textblocks | slice:0:round">
    {{textblock?.hello}}
</li>

Plunkerhttp://plnkr.co/edit/KizxAHaD70kac2XB2go9?p=preview

【讨论】:

  • plunker 链接对我来说已损坏。
  • @varunaaruru 是的,刚刚修复它 :-) 感谢您的通知
  • 这是一个很好的解决方案。如果您只想显示一些元素并且没有内置文本块,您可以在此处组合使用此回复:stackoverflow.com/a/38249801/1626443
猜你喜欢
  • 2013-04-28
  • 2019-11-03
  • 2015-03-29
  • 2020-01-16
  • 1970-01-01
  • 2022-07-04
  • 1970-01-01
  • 2018-10-06
  • 2017-06-24
相关资源
最近更新 更多