1

i'm using Ionic 2 Framework and so Angular 2 and Ts.

In my ts file i have a variable, let's say 'round' and an object 'textblocks'

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

'Round' value is changing during the life of the application (0 to 3).

Then in my html file, I have a list:

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

I can use a ngFor to display as much 'li' as the number in the variable 'round', each displaying the text in the corrispondent textblocks[round].hello, with 'round' increasing while the view is used?

Example when round is 1

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

that is

  • hi
  • there

Example when round is 3

<ul>
  <li>{{textblocks[0].hello}}</li>   
  <li>{{textblocks[1].hello}}</li> 
  <li>{{textblocks[2].hello}}</li> 
  <li>{{textblocks[3].hello}}</li>       
</ul>
  • hi
  • there
  • john
  • doe
Sasha Grievus
  • 2,566
  • 5
  • 31
  • 58
  • Looks like a dup of https://stackoverflow.com/questions/36535629/repeat-html-element-multiple-times-using-ngfor-based-on-a-number – Günter Zöchbauer May 24 '17 at 11:11
  • nope. I found that answer ,previously, but it doesn't take into account the 'variable' issue. It explains how to repeat an element a fixed amount of times (and the answer are far more complicate than the one provided by trichetriche here) – Sasha Grievus May 24 '17 at 12:16

2 Answers2

4

Yes you can, like so

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

And you can replace the span with a <template></template> but I don't remember the exact syntax, so I used a span

  • Good to know! Thank you! – Sasha Grievus May 24 '17 at 12:13