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 asconst indexes = count => [...Array(count).keys()]
– Reuven Chacha Commented Jan 23, 2018 at 21:20
1 Answer
Reset to default 3As 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
版权声明:本文标题:javascript - Angular 4 - Loop through HTML markup - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745164998a2645629.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论