4

How would I go about writing a while loop, doing the equiv of

while (x--) {
  <li> foo {{x}} </li>
}

with a "microsyntax" similar to *ngFor but for looping with an incrementer or decrementer rather than over an object. So if component has x = 5. And I want

<li> foo 5 </li>
<li> foo 4 </li>
<li> foo 3 </li>
<li> foo 2 </li>
<li> foo 1 </li>

Or the like. Template Toolkit does this with WHILE. I'm looking for that kind of functionality. So does jade/Pugs.

8
  • 1
    *ngFor is for looping in template if you not explored yet Commented Sep 8, 2017 at 20:23
  • @AniruddhaDas right, I want to loop in templates with a while. Commented Sep 8, 2017 at 20:25
  • is not that possible with *ngFor? Commented Sep 8, 2017 at 20:27
  • like <li *ngFor="let foo of foos">{{foo}}<li> Commented Sep 8, 2017 at 20:28
  • @AniruddhaDas not afaik. Feel free to show me how, if it is. ngFor loops over iterators as far as I can see. Commented Sep 8, 2017 at 20:28

2 Answers 2

0

If you want to count up, *ngFor has an index value available to you. I am not aware of a way to count downwards though.

<li *ngFor="let foo of foos; let i = index">
 foo {{i}}
</li>

Output:

foo 0
foo 1
foo 2
foo 3
foo 4
Sign up to request clarification or add additional context in comments.

5 Comments

Can you show what you're setting foos too? Is that foos=5?
It's a collection of your choice. If you are looking to do this with just a number of times you want to increment, there is unfortunately no easy way to do this. See this question.
Well, I was really looking for an ngWhile or the like, not to force this to work with ngFor =(
ngFor is the only type of templating loop. So you might just be stuck using it. Maybe if you provide more details about your specific problem someone could provide a better approach for your situation?
I'm trying a list of elements from a counter. I feel like I could do this in the 1950s with perl
0

It loops through an array, put whatever you want in the array's functions:

<li *ngFor="let foo of foos.slice(0, 5)">
 foo {{i}}
</li>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.