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>
3
  • 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 Commented Mar 31, 2019 at 22:14
  • 1
    Take a look at How can I use NgFor without creating arrays to generate matrix UI pattern. Commented Mar 31, 2019 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. Commented Mar 31, 2019 at 22:22

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.