admin管理员组

文章数量:1415491

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!

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!

Share Improve this question asked Jan 23, 2018 at 20:29 sayayinsayayin 1,0416 gold badges25 silver badges43 bronze badges 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()] – Reuven Chacha Commented Jan 23, 2018 at 21:20
Add a ment  | 

1 Answer 1

Reset to default 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>

本文标签: javascriptAngular 4Loop through HTML markupStack Overflow