1

In my app.component.tsI have a variable of type number like so

somevar: number = 3

I am trying to loop over it in my app.component.html and do something three time (in this case, since somevar is 3).

Is this possible since the variable is not an array in which case this would be trivial using the ngIf directive.

I tried something like below -but that's pretty idiotic and doesn't work, of course.

<div *ngFor="let i = somevar; while i > 0; i--">
   <span>+</span>
</div>
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • 1
    i know its not the perfect solution but you could create and empty array of length somevar and iterate over that also I checked angulars documentation and it says int works only for iterables – jonathan Heindl Mar 31 '19 at 22:14
  • 1
    Take a look at [How can I use NgFor without creating arrays to generate matrix UI pattern](https://stackoverflow.com/q/36621771/1009922). – ConnorsFan Mar 31 '19 at 22:15
  • @jonathanHeindl I used that approach for another similar scenario. Was just wondering if there is another way that I'm not aware of. –  Mar 31 '19 at 22:22

1 Answers1

2

Here is one way to do it wihouth adding a method or an array variable in the component class. It creates a string by repeating a character somevar times, and converts the string to an array of characters, which can be iterated with ngFor.

<div *ngFor="let item of 'x'.repeat(somevar).split('')">
   <span>+</span>
</div>

See this stackblitz for a demo.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146