Search code examples
angularangular-directive

Looping over a non-array variable with ngFor


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>

Solution

  • 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.