2

I'm moving from ReactJS to Angular 4. I need to loop around some html markup so I don't have to re-type it. Only thing changes with each item is that that I need to generate html attributes e.g ids etc based on the loop index. So basically something like below. How should I handle this in Angular? Don't think I need to to use *ngFor here. I don't have an array of data, just need to loop for a finite number of times. In ReactJS I usually would have a function return the html like this:

const itemCount = 12;

let itemMarkup = [];

for (let i = 1; i <= itemCount; i++) {
  itemCount.push(
    <div id={`itemi`}>Item i</div>
  )
}
return itemMarkup ;

Thanks!

1
  • Appending html dynamically is not a best practice in the 'Angular' way. In such case it would be better to stick to *ngFor and create a method that creates a list of indexes to iterate over, such as const indexes = count => [...Array(count).keys()] Commented Jan 23, 2018 at 21:20

1 Answer 1

3

As you noted, *ngFor only works on iterables. However, it also gives you easy access to the index of each item. In your .ts file:

this.itemCount = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

(or your preferred way of generating an array from a range)

And then in .html/template:

<div *ngFor="let item of itemCount; let i=index">
  <div id="item{{i}}">Item {{i}}</div>
</div>

Or put it all in your template:

<div *ngFor="let item of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; let i=index">
  <div id="item{{i}}">Item {{i}}</div>
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer but I was hoping there was a different way of handling this without having to create an array of items just because I need to iterate and need an index.
As Reuvan mentioned in the comments, ngFor is how you repeat html elements in Angular. Angular approaches this problem from a different mindset than React: Angular manages the DOM with functions (directives such as ngFor), whereas React, as you know, is more interwined with the DOM. This difference in approach is part of why creating that array for the purposes of iterating makes sense within an Angular app.

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.