Angular2生成器功能 [英] Angular2 generator function
问题描述
在Angular2应用中,我想在模板中的startDate
和endDate
之间进行整天的迭代.像这样:
In an Angular2 app, I would like to iterate over all days between startDate
and endDate
in a template. Something like this:
<div *ngFor="let date of dateRange(startDate,endDate)">
{{date}}
</div>
我意识到我可以预先计算所有这些日期,并在显示它们之前将它们存储在数组中,但是我宁愿不占用内存.我一直在阅读javascript 生成器功能似乎在普通javascript中,我可以做到这一点:
I realize that I could precalculate all these dates and store them in an array before displaying them, but I would rather not take up the memory. I have been reading up on javascript generator functions and it seems like in vanilla javascript, I could do this:
function* dateRange(start,end) {
let cur = start;
while (cur <= end) {
yield cur;
cur.setDate(cur.getDate() + 1);
}
}
有没有办法在Angular2组件中使用可以在模板迭代器中使用的生成器函数?
Is there any way to use a generator function like this from within an Angular2 component which could be used in a template iterator?
推荐答案
我可以预先计算所有这些日期,然后在显示它们之前将它们存储在数组中,但我不想占用内存
that I could precalculate all these dates and store them in an array before displaying them, but I would rather not take up the memory
任何内存都将远远少于所有具有dom元素的DOM使用的内存.
Any memory will be much much less than the memory used by the DOM with all those dom elements.
我能想到的唯一解决方案是在使用ngFor
之前在生成器中制作一个数组,这时为什么不只使用数组.
The only solution I can think of is making an array out of the generator before using ngFor
and at that point why no just only use an array.
这篇关于Angular2生成器功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!